Fixed memory leaks and other small cleanups