make writeGlobalState more robust

State is now written to a temporary file and moved into place, making
the operation of writing the state atomic.