function DENS = measdens (N,L,R,S,ntotalA,ntotalB)

DENS = zeros(N,2);

for j = 2:N-2
    disp (['MeasDens J = ', num2str(j)]);
    
    BL = L(j-1);
    SL = S(j);
    SR = S(j+1);
    BR = R(N-j-1);
    
    IBL = speye(BL.m);
    IBR = speye(BR.m);
    ISL = speye(SL.m);
    ISR = speye(SR.m);

    G = superblock (BL,SL,SR,BR,ntotalA,ntotalB);

    [X1,X2,X3,X4] = ndgrid (BR.NTOTA,SR.NTOTA,SL.NTOTA,BL.NTOTA);
    MA = X1+X2+X3+X4;
    [X1,X2,X3,X4] = ndgrid (BR.NTOTB,SR.NTOTB,SL.NTOTB,BL.NTOTB);
    MB = X1+X2+X3+X4;
    IND = find ((MA == ntotalA) & (MB == ntotalB));
    
    G = G(IND);
    
    if j == 2
        NL = kron (BL.NA,ISL);
        NR = kron (ISR,IBR);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(1,1) = NP;
        
        NL = kron (BL.NB,ISL);
        NR = kron (ISR,IBR);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(1,2) = NP;
    end
   
    if j == N-2
        NL = kron (IBL,ISL);
        NR = kron (SR.NA,IBR);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(N-1,1) = NP;
        
        NL = kron (IBL,ISL);
        NR = kron (ISR,BR.NA);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(N,1) = NP;

        NL = kron (IBL,ISL);
        NR = kron (SR.NB,IBR);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(N-1,2) = NP;

        NL = kron (IBL,ISL);
        NR = kron (ISR,BR.NB);
        NO = subkron (NL,NR,IND);
        NP = G'*NO*G;
        DENS(N,2) = NP;
    end

    NL = kron (IBL,SL.NA);
    NR = kron (ISR,IBR);
    NO = subkron (NL,NR,IND);
    NP = G'*NO*G;
    DENS(j,1) = NP;
    
    NL = kron (IBL,SL.NB);
    NR = kron (ISR,IBR);
    NO = subkron (NL,NR,IND);
    NP = G'*NO*G;
    DENS(j,2) = NP;
end
