Assorted tweaks to code

Most are intended to make the code easier to read.  

Commit 4190a27 is potentially an improvement, since writing files via the `with` statement guarantees that the file is closed when the block is exited.