Refactored code to remove leaks and clean up the code.