def idxfold(dlist, idx):
    """ Find the index corresponding to the folded version of a tensor from the flatten version

    :param list,int dlist: list of integers containing the dimensions of the tensor
    :param int idx: tensor flatten index

    :returns: list of int -- the index for the folded version

    :note: this routine can be used to get the indexes of a TTmat from indices of a matkron (matrix obtained using np.kron): (i,j) \\in N^d x N^d -> ((i_1,..,i_d),(j_1,..,j_d)) \\in (N x .. x N) x (N x .. x N)

    """
    n = len(dlist)
    cc = [1]
    for val in reversed(dlist):
        cc.append(cc[-1] * val)
    if idx >= cc[-1]:
        raise NameError('TensorToolbox.core.idxunfold: Index out of bounds')
    ii = []
    tmp = idx
    for i in range(n):
        ii.append(tmp // cc[n - i - 1])
        tmp = tmp % cc[n - i - 1]
    return tuple(ii)
