fix a bunch of memory leaks and other bugs