Factor out tempfile creation and use TMPDIR