proper cleanup of tempfiles

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