Fixed various memory leaks and resource deallocation problems.
Merge pull request #1434 from akallabeth/memleak_fixes

Fixed various memory leaks and resource deallocation problems.