To fix the point you brought up, about having the program fail and leave behind a file, you can always add a point at the beginning to check to see if there is a temporary file, and if so delete it. This would ensure that the next time you draw from the temporary file you don't get the wrong info. To do this you use a "modified" if statement.
if exist temp.file del temp.file
I like to add the /f switch to 'del' in case some other program decides it needs to read the file at that exact time (which has happened to me more times than I like to think about.)