reformat code and clean up some bugs