fixed memory access errors and added a safer method to close file streams