Refactored more sorting code.