move file writing to helper function