refactored sorting