refactoring and new sort function