Cleaned up code, fixed some bugs