Fix many many code quality issues.

Hi all, this PR cleans up a bunch more code. Please test it out on your use cases, **and write unit tests for any broken parts** to ensure that they aren't broken again. None of us should have to guess whether or not an innocent looking change breaks somebody else's code. Write a test, and it I (or anyone else) break it, then its my job to fix the breakage.

Thanks,
K