Cleanup and fixed a bunch of things

I'm trying to organize the code into manageable blocks. Right now it is really a huge piece of code, and it's hard to understand how different parts work together. I've also rewritten a few small parts to be more straightforward / more pythonic.