Fixed some memory leaks, modified file opening code