fix a bunch of bugs and improvements