Refactor saving temporary file, related utils