clean up code, fix a few bugs