make sure the tmp file is closed before moving

this should fix all the issues we've had with temporary files being moved across file systems (the rest was taken care of by contributed pull requests)