Returns a list of sorted states, original states list remains unsorted

    The sort list is a list of state field: field key pairs
        For example (as YAML):
            - data: position
            - meta: created_at
    The field_key part can be a list to simplify input
        - meta: created_at
        - meta: updated_at
    or
        - meta:
            - created_at
            - updated_at

    
    It is also possible to sort by grouping values
        For example, with a grouping called student_id:
        - groupings:
            - student_id:
                index: !!null     (optional: when null or missing it uses the first group in the grouping
                values:
                    - meta: student_id

    A key which begins with a - inverts the sort, so
        - -data: position
    is the inverse of
        - data: position

    With groupings only values can have a - to invert the sort (always on the key)
        - groupings:
            - student_id:
                index: !!null
                values:
                    - -meta: student_id
    NOT
        - -groupings: ...

def sort_states(states, sort_list):
    """
    Returns a list of sorted states, original states list remains unsorted

    The sort list is a list of state field: field key pairs
        For example (as YAML):
            - data: position
            - meta: created_at
    The field_key part can be a list to simplify input
        - meta: created_at
        - meta: updated_at
    or
        - meta:
            - created_at
            - updated_at

    
    It is also possible to sort by grouping values
        For example, with a grouping called student_id:
        - groupings:
            - student_id:
                index: !!null     (optional: when null or missing it uses the first group in the grouping
                values:
                    - meta: student_id

    A key which begins with a - inverts the sort, so
        - -data: position
    is the inverse of
        - data: position

    With groupings only values can have a - to invert the sort (always on the key)
        - groupings:
            - student_id:
                index: !!null
                values:
                    - -meta: student_id
    NOT
        - -groupings: ...
        

    """
    sorted_states= states.copy()
    for sort_pair in reversed( _convert_list_of_dict_to_tuple(sort_list) ):
        if sort_pair[0].lstrip('-') in ['data','measure','meta']:
            sorted_states= _state_value_sort(sorted_states, sort_pair, _state_key_function)
        elif sort_pair[0] == 'groupings':
            for grouping in reversed(sort_pair[1]):
                sorted_states= _groupings_values_sort(sorted_states, grouping)
    return sorted_states