def merge_ranges(ranges, max_gap):
    """
        Merge ranges which are closer than max_gap
    """
    merged_ranges = []
    for range in ranges:
        if merged_ranges:
            curr_start, curr_end = range
            # compare against last interval in merged_ranges
            pre_start, pre_end = merged_ranges[-1]
            if curr_start - pre_end < max_gap:
                # merge current range with the last range in the list
                merged_ranges[-1] = (pre_start, max(curr_end, pre_end))
            else:
                # append the new range to current one
                merged_ranges.append(range)
        else:
            # no merged ranges - just add this one
            merged_ranges.append(range)

    return merged_ranges