better cleanup of tempfiles

I've tried to improve the cleanup of tempfiles (supersedes #4870).

\- Felix