Fixed bug and cleaned up code