some simplification and better handling of an edge case in writeFile