refactor sort code, bugfix