Fixes for things that might actually break

I've not seen these failures reported as user-visible symptoms, but the code is still wrong.
The fixes are mixed up with some clean-ups.