Use flake8 to check code formatting

Most of these code changes are automatic via [autopep8](https://github.com/hhatto/autopep8), but some manual changes were required.