Improve testing

A few places where I found testing to be inadequate, and then some refactorings I came up with in the process.