def reorder_buckets(old_buckets, permutation):
    """
    Transforms bucket list according to the new order given by
    permutation. The variables are renamed and buckets are reordered
    to hold only gates acting on variables with strongly increasing
    index.

    Parameters
    ----------
    old_buckets : list of lists
          old buckets
    permutation : list
          permutation of variables

    Returns
    -------
    new_buckets : list of lists
          buckets reordered according to permutation
    label_dict : dict
          dictionary of new variable objects
          (as IDs of variables have been changed after reordering)
          in the form {old: new}
    """
    # import pdb
    # pdb.set_trace()
    if len(old_buckets) != len(permutation):
        raise ValueError('Wrong permutation: len(permutation)'
                         ' != len(buckets)')
    perm_dict = {}
    for n, idx in enumerate(permutation):
        if idx.name.startswith('v'):
            perm_dict[idx] = idx.copy(n)
        else:
            perm_dict[idx] = idx.copy(n, name=idx.name)

    n_variables = len(old_buckets)
    new_buckets = []
    for ii in range(n_variables):
        new_buckets.append([])

    for bucket in old_buckets:
        for tensor in bucket:
            new_indices = [perm_dict[idx] for idx in tensor.indices]
            bucket_idx = sorted(
                new_indices, key=int)[0].identity
            # we leave the variables permuted, as the permutation
            # information has to be preserved
            new_buckets[bucket_idx].append(
                tensor.copy(indices=new_indices)
            )

    return new_buckets, perm_dict