Miscellaneous cleanups

A collection of patches for several unrelated bugs and fragilities spotted in a read-through of the code -- plus a few refactorings while I was at it.

Most of these patches are untested; the pull request format seems the most convenient way to share the observations about the code, but they definitely shouldn't be merged without checking.