[PM] Fix a bunch of bugs I spotted by inspection when working on this
code. Copious tests added to cover these cases.