Refactor writing to files.