refactor sort code