File writing is moved into a routine