Cleaned up code and fixed some minor bugs.