Refactored code

Here's my cleaned up version of your code. Make sure to look through the commits to get the general idea of what's happening. I tried to be explicit in my commit messages, but if you have any questions, feel free to let me know.

By way of general theory, I tend to like breaking things out into single-purpose functions. That way, you can almost read the code without having to resort to a lot of comments.