Fix memory leaks

Fixes a bunch of memory leaks all over the place and cleans up some cruft.