Later in the loop several files are added to unsorted_files.  It will loop over those aswell unless you copy the list.  This change reduces the number of loops..