Minor modifications.
Multiple changes to reduce duplicate code, output all temporary files to TMP_DIR, and reduce moving of files via system calls.