I spent a bunch of time tinkering with this, mostly to understand what the tests check and thus the expected behavior. I came up with the attached patch, based on top of this one: it isn't necessarily an improvement, although it does get rid of the recursion (which I don't like). I left all the debug traces in, it isn't a clean patch by any means, but I think it shows a possible direction for the implementation. I haven't checked that it still works (or even that it still makes sense) with the other patches in the series.