Fixed various memory leaks and resource deallocation problems.