Some refactoring on sorting and filtering code to eliminate duplicate code.