Fix the memory leak and actually close the resources.
Merge pull request #1898 from ratnikov/fix-memory-leak

Fix the memory leak and actually close the resources.