Cleanups and error fixes suggested by flake8 (pep8 + pyflakes)

A lot of whitespace cleanups (not all long lines are broken up); fixes to several bugs caught by pep8 and pyflakes.