Fixes for writeDirtyToDisk.

This commit fixes two issues in the writeDirtyToDisk function:

First, closing the temporary files is now done using a defer, so they
are always closed.

Second, the various account mutexs are no longer unlocked using a
defer, preventing more than one from being held at once and causing a
deadlock caused by incorrect locking order.