Move file writing code to util to avoid duplication. Do not mark a file as saved if an error has happened.