Fixed memory leaks and other minor cleanups

This makes it possible to actually use valgrind to check for memory leaks in your own code.