Fixed memory leaks and file handle leaks.