fix bunch of bugs and typos, import errors, apply pyflakes