refactored sort creation code