Added code to prevent file corruption upon a failed write by rewriting
the old contents back into the file.