function A = hss2mat(D,U,R,B,W,V,tr,UL)

n = length(tr);
lv = hsslevel(tr);
ch = child(tr);

cl = [];
k = 0;
l(1) = 1;
for i = 1:n
    if isempty(ch{i})
        k = k+1;
        cl(k) = i;
        m(k) = size(D{i},1);
        l(k+1) = l(k)+m(k);
    end
end

A = zeros(l(end)-1,l(end)-1);
for i = 1:k
    ii = cl(i);
    A(l(i):l(i+1)-1,l(i):l(i+1)-1) = D{ii};
    
    if nargin < 8
        jr = [1:i-1 i+1:k];
    elseif upper(UL) == 'U'
        jr = i+1:k;
    else
        jr = 1:i-1;
    end
    for j = jr
        ii = cl(i); jj = cl(j);
        T1 = U{ii}; T2 = V{jj};
        while lv(ii) > lv(jj)
            T1 = T1*R{ii}; ii = tr(ii);
        end
        while lv(ii) < lv(jj)
            T2 = T2*W{jj}; jj = tr(jj);
        end
        while tr(ii) ~= tr(jj)
            T1 = T1*R{ii}; ii = tr(ii);
            T2 = T2*W{jj}; jj = tr(jj);
        end
        A(l(i):l(i+1)-1,l(j):l(j+1)-1) = T1*B{ii}*T2';
    end
end