Fixed a few memory leaks and bugs.