Fixed memory leaks and bugs.