fixed some bugs and cleaned up code.