Added some error checking and proper temporary file cleanup.