fixed some bugs and cleaned some code