sort function & refactor code