def merge_pieces(gamma, right, values, dists, mu_dist, max_size):
    """
    Combine consecutive intervals in Potts model solution, if doing
    that reduces the cost function.
    """
    mu, dist = mu_dist.mu, mu_dist.dist
    right = list(right)
    while True:
        min_change = 0
        min_change_j = len(right)
        l = 0
        for j in range(1, len(right)):
            if min_change_j < j - 2:
                break
            change = dist(l, right[j] - 1) - (dist(l, right[j - 1] - 1) +
                dist(right[j - 1], right[j] - 1) + gamma)
            if change <= min_change:
                min_change = change
                min_change_j = j - 1
            l = right[j - 1]
        if min_change_j < len(right):
            del right[min_change_j]
        else:
            break
    l = 0
    for j in range(1, len(right)):
        prev_score = dist(l, right[j - 1] - 1) + dist(right[j - 1], right[j
            ] - 1)
        new_off = 0
        for off in range(-max_size, max_size + 1):
            if right[j - 1] + off - 1 <= l or right[j - 1] + off >= right[j
                ] - 1 or off == 0:
                continue
            new_score = dist(l, right[j - 1] + off - 1) + dist(right[j - 1] +
                off, right[j] - 1)
            if new_score < prev_score:
                new_off = off
                prev_score = new_score
        if new_off != 0:
            right[j - 1] += new_off
        l = right[j - 1]
    l = 0
    values = []
    dists = []
    for j in range(len(right)):
        dists.append(dist(l, right[j] - 1))
        values.append(mu(l, right[j] - 1))
        l = right[j]
    return right, values, dists
