working version, corrected final loops, added temp directory removal