Cleaned up code and fixed a few small bugs.