Improve toTempFile function