fix some bugs, tidy up some code