This function takes a list of row-ranges (as returned by `_parse_row`)
    ordered by rows, and produces a list of distinct rectangular ranges
    within this grid.

    Within this function we define a 2d-range as a rectangular set of cells
    such that:
      - there are no empty rows / columns within this rectangle;
      - the rectangle is surrounded by empty rows / columns on all sides;
      - no subset of this rectangle comprises a valid 2d-range;
      - separate 2d-ranges are allowed to touch at a corner.

def _combine_ranges(ranges):
    """
    This function takes a list of row-ranges (as returned by `_parse_row`)
    ordered by rows, and produces a list of distinct rectangular ranges
    within this grid.

    Within this function we define a 2d-range as a rectangular set of cells
    such that:
      - there are no empty rows / columns within this rectangle;
      - the rectangle is surrounded by empty rows / columns on all sides;
      - no subset of this rectangle comprises a valid 2d-range;
      - separate 2d-ranges are allowed to touch at a corner.
    """
    ranges2d = []
    for irow, rowranges in enumerate(ranges):
        ja = 0
        jb = 0
        while jb < len(rowranges):
            bcol0, bcol1 = rowranges[jb]
            if ja < len(ranges2d):
                _, arow1, acol0, acol1 = ranges2d[ja]
                if arow1 < irow:
                    ja += 1
                    continue
                assert arow1 == irow or arow1 == irow + 1
            else:
                acol0 = acol1 = 1000000000

            if bcol0 == acol0 and bcol1 == acol1:
                ranges2d[ja][1] = irow + 1
                ja += 1
                jb += 1
            elif bcol1 <= acol0:
                ranges2d.insert(ja, [irow, irow + 1, bcol0, bcol1])
                ja += 1
                jb += 1
            elif bcol0 >= acol1:
                ja += 1
            else:
                assert ja < len(ranges2d)
                ranges2d[ja][1] = irow + 1
                if bcol0 < acol0:
                    ranges2d[ja][2] = bcol0
                if bcol1 > acol1:
                    ranges2d[ja][3] = acol1 = bcol1
                    ja = _collapse_ranges(ranges2d, ja)
                jb += 1
    return ranges2d