def group_according_to_gap(flat_list,gaps,max_gap,max_group_size):
    """ 
    Splits a python list into groups by their gaps in time, using a list of
    gaps between them.
    Inputs:
        flat_list = python list, shape [n]
        gaps = numeric list, shape [n-1], descibing gaps between elements of flat_list
        max_gap = maximum gap allowed between list elements
        max_group_size = maximum number of list elements per group
    Returns:
        List of lists that contain groups of input list elements
    """    
    within_gap = gaps <= max_gap
    groups = list()
    group_gaps = list()
    sub_group = list()
    sub_gaps = list()
    sub_group.append(flat_list[0])
    for i in range(len(gaps)):
        if ~within_gap[i] or len(sub_group) >= max_group_size:
            groups.append(sub_group)
            if not sub_gaps:
                sub_gaps.append((None,))
            group_gaps.append(sub_gaps)
            sub_group = []
            sub_gaps = []
        else:
            sub_gaps.append(gaps[i])
        sub_group.append(flat_list[i+1])
    groups.append(sub_group)
    if not sub_gaps:         
        sub_gaps.append((None,))
    group_gaps.append(sub_gaps)
    # returning (list of file lists, list of gap time lists)
    return (groups, group_gaps)