Factor out sorting