Adding sort support and refactoring