refactored code so writing the file has become its own function