Fixed bugs and cleaned up code