import copy


def merge_overlap(intervals, spacer=0):
    """ Merge overlapping intervals. Take a list of lists of 2 elements, [start, stop],
    check if any [start, stop] pairs overlap and merge if any. Return the merged [start, stop]
    list."""
    exons = copy.deepcopy(intervals)
    exons = [e for e in exons if len(e) == 2]
    for e in exons:
        e.sort()
    exons.sort()
    if len(exons) < 2:
        return exons
    # reuse a piece of code from get_exons:
    #######################################
    overlapping = 1
    while overlapping:
        overlapping = 0
        for i in range(len(exons)):
            e = exons[i]
            for j in range(len(exons)):
                x = exons[j]
                if i == j:
                    continue
                else:
                    if e[1] >= x[1]:
                        if (e[0] - x[1]) <= spacer:
                            overlapping = 1
                    elif x[1] >= e[1]:
                        if (x[0] - e[1]) <= spacer:
                            ovrelapping = 1
                    if overlapping:
                        # merge exons and add to the exon list
                        exons.append([min(e[0], x[0]), max(e[1], x[1])])
                        # remove the exons e and x
                        exons.remove(e)
                        exons.remove(x)
                        # once an overlapping exon is found, break out of the for loop
                        break
            if overlapping:
                # if an overlapping exon is found, stop this for loop and continue with the
                # while loop with the updated exon list
                break
    exons.sort()
    return exons