refactor writing to file