I'll admit to not really following what the code does, so will really need
someone with a better understanding of the aim of this code to look over the
proposed fix; but based on a bunch of runs and hand-debugging, this seems to
do the job.
This passes all existing tests and also removes the reported error.
On the other hand I'm not confident that I'm *not* just masking an
underlying issue with this function.