def clip_timetable(timetable, clip_start=None, clip_end=None, pending=None):
    """Generates a timetable by clipping entries from the given *timetable*.
    Entries ending before *clip_start* are discarded as well as entries
    starting after *clip_end*. Start and end times of entries lying on the
    boundaries modified to match *clip_start* resp. *clip_end*. Entries on the
    *clip_end* are added to the list *pending*, if it is supplied."""
    if pending is None:
        pending = []
    idx = 0
    while idx < len(pending):
        start, end, value = pending[idx]
        if clip_start is not None:
            if end <= clip_start:
                pending.pop(idx)
                continue
            if start < clip_start:
                start = clip_start
        if clip_end is not None:
            if start >= clip_end:
                break
            if end > clip_end:
                end = clip_end
        yield start, end, value
        if clip_end is not None and pending[0][1] > clip_end:
            idx += 1
        else:
            pending.pop(idx)
    for entry in timetable:
        start, end, value = entry
        if clip_start is not None:
            if end <= clip_start:
                continue
            if start < clip_start:
                start = clip_start
        if clip_end is not None:
            if start >= clip_end:
                pending.append(entry)
                break
            if end > clip_end:
                end = clip_end
                pending.append(entry)
        yield start, end, value
