Fix tempfile behaviour.

1. Move setting TMPDIR to earlier in the script;
2. Introduce the random function;
3. Replace /tmp/stderr by a 'true' tempfile;
4. Use the random function in generating the tmpdir too;
5. Trap a few signals so that the script cleans up after itself.
Merge pull request #2 from daenney/tempfile

Fix tempfile behaviour.