Fixing a problem to do with not closing files properly