Holy crap, it's done. Still kind of ugly, but oh well.
Cleaned up code, added comments.