Cleaned up code and fixed some bugs