Cleaned up code and fixed bugs