Thanks for the patch. I improved it, wrote a NEWS entry and a test case for it, and installed the attached. I think this finishes off the issues in Bug#36502 and so am closing the bug report.