Fixes for things that might actually break, plus some performance tweaks.

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