added code to close files when appropriate