Fixed tempfile creation and added tempfile removal as suggested by Matthijs/Vlad.