def sort_windows_on_channel_and_location(sta_win):
    """
    functions for merge_instruments_window. the windows
    will be sorted based on [chan][location]

    :param sta_win:
    :return:
    """
    sort_dict = {}
    for trace_id, trace_win in sta_win.items():
        chan = trace_id.split('.')[-1][0:2]
        loc = trace_id.split('.')[-2]
        if chan not in sort_dict:
            sort_dict[chan] = {}
        if loc not in sort_dict[chan]:
            sort_dict[chan][loc] = {'traces': [], 'nwins': 0}
        sort_dict[chan][loc]['traces'].append(trace_id)
        sort_dict[chan][loc]['nwins'] += len(trace_win)
    for chan, chan_info in sort_dict.items():
        for loc, loc_info in chan_info.items():
            loc_info['traces'] = sorted(loc_info['traces'])
    return sort_dict
