Cleaned up some code and fixed a few bugs