finish insert function, fix a bunch of bugs