Factor out secondary sort