This block looks like it was copied from writeFile maybe?  We should move it out to a separate function and have both places call it.