Moving Process Cleanup Code

Moved cleanup code outside the loop so the cleanup code and loop are cleaner