refactored code to make sorting work properly