Explicitly check if tmpfile is nil before calling close

Fixes #246