Fixed various bugs and cleaned up some code