Sorting and filtering logic