Refactor, and fix pep8 errors and pyflakes errors