Improvements to sorting logic