Mostly PEP8 cleanups in the course of reading the code.

I took the liberty of adding a few specific exception types, some
documentation, and things like that, but this is mostly a cosmetic change.