Fixed some random bugs and cleaned up the code a bit.