Fixed memory leaks and unclosed files

subj