Cleaned up code and fixed minor bugs.