fixed a few bugs and cleaned up the code