def prepare_search_groups(events, source_duration, chapter_times, max_ts_duration, max_ts_distance):
    last_unlinked = None
    for idx, event in enumerate(events):
        if event.is_comment:
            try:
                event.link_event(events[idx+1])
            except IndexError:
                event.link_event(last_unlinked)
            continue
        if (event.start + event.duration / 2.0) > source_duration:
            logging.info('Event time outside of audio range, ignoring: %s' % unicode(event))
            event.link_event(last_unlinked)
            continue
        elif event.end == event.start:
            logging.debug('{0}: skipped because zero duration'.format(format_time(event.start)))
            try:
                event.link_event(events[idx + 1])
            except IndexError:
                event.link_event(last_unlinked)
            continue

        # link lines with start and end times identical to some other event
        # assuming scripts are sorted by start time so we don't search the entire collection
        same_start = lambda x: event.start == x.start
        processed = next((x for x in takewhile(same_start, reversed(events[:idx])) if not x.linked and x.end == event.end),None)
        if processed:
            event.link_event(processed)
        else:
            last_unlinked = event

    events = (e for e in events if not e.linked)

    search_groups = merge_short_lines_into_groups(events, chapter_times, max_ts_duration, max_ts_distance)

    # link groups contained inside other groups to the larger group
    passed_groups = []
    for idx, group in enumerate(search_groups):
        try:
            other = next(x for x in reversed(search_groups[:idx])
                         if x[0].start <= group[0].start
                         and x[-1].end >= group[-1].end)
            for event in group:
                event.link_event(other[0])
        except __HOLE__:
            passed_groups.append(group)
    return passed_groups
dataset/ETHPy150Open tp7/Sushi/sushi.py/prepare_search_groups