Sorting refactored and commented