Fixed infinite loop bug, improved the cleanup of files left behind