Changes to file handling

Only open files when necessary and close them when done writing.