Moved file writing functionality to a separate function in a separate file.