fixed bugs and cleaned up code