I don't know whether this fixes the bug reported, since there's no test, but it looks correct on inspection and the tests we have are passing. Okay to merge.