Memory leak and file handle leak fix