refactored code for better sorting.