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 chance.
Manual merge of abingham pull request
Merge branch 'abingham-rewrite' into rewrite