I wrote a fix and added a test, please review. I did not touch the situation discussed in P.S. (should I maybe create a separate issue for that?), this only fixes the problem reported.