don't write unless necessary
some minor code cleanup, also don't overwrite name if already known on errors
moved xml wrap code