Fix a bunch of memory leaks and stuff.