function BRO = getright (BL,SL,SR,BR,G)

global JA JB tmax wlimit;

ml = BL.m*SL.m;
mr = BR.m*SR.m;

GM = reshape(G,mr,ml);  % density matrix calculation
DM = full (GM*GM');

DM = (DM + DM')/2;

JSR = ones(SR.m,1);
JBR = ones(BR.m,1);
[X1,X2] = ndgrid (BR.NTOTA,SR.NTOTA);
NTOTA = X1+X2; NTOTA = NTOTA(:);
[X1,X2] = ndgrid (BR.NTOTB,SR.NTOTB);
NTOTB = X1+X2; NTOTB = NTOTB(:);

V = zeros(mr,mr);
D = zeros(mr,1);
SA = uint16(zeros(mr,1));
SB = uint16(zeros(mr,1));

i = 1;
for IA = unique (NTOTA')
    for IB = unique (NTOTB')
        IND = find ((NTOTA == IA) & (NTOTB == IB));
        n = size(IND,1);
        DMX = DM(IND,IND);
        [V0,D0] = eig(DMX);
        VX = zeros(mr,n);
        VX(IND,:) = V0;
        DX = diag(D0,0);
        SXA = IA*uint16(ones(n,1));
        SXB = IB*uint16(ones(n,1));
        I = i:(i+n-1);
        V(:,I) = VX;
        D(I) = DX;
        SA(I) = SXA;
        SB(I) = SXB;
        i = i+n;
    end;
end;

[D,IX] = sort (D,'descend');
V = V(:,IX);
SA = SA(IX);
SB = SB(IX);

F = find (1 - cumsum(D) < wlimit);
IND = transpose (1:F(1));
n = size(IND,1);

if (n <= tmax)
    BRO.m = n;
    BRO.NTOTA = SA(IND);
    BRO.NTOTB = SB(IND);
    O = V(:,IND);
else
    BRO.m = tmax;
    BRO.NTOTA = SA(1:tmax);
    BRO.NTOTB = SB(1:tmax);
    O = V(:,1:tmax);
    disp (['Right block size = ', num2str(BRO.m)]);
end

O = sparse(O);
IBR = speye(BR.m);
ISR = speye(SR.m);

CA = kron(SR.CA,IBR);
CB = kron(SR.CB,IBR);
BRO.CA = O'*CA*O;
BRO.CB = O'*CB*O;

NA = kron(SR.NA,IBR) + kron(ISR,BR.NA);
NB = kron(SR.NB,IBR) + kron(ISR,BR.NB);
BRO.NA = O'*NA*O;
BRO.NB = O'*NB*O;

H = kron(ISR,BR.H) + kron(SR.H,IBR) - JA*(kron(SR.CA,BR.CA') + kron(SR.CA',BR.CA)) - JB*(kron(SR.CB,BR.CB') + kron(SR.CB',BR.CB));
BRO.H = O'*H*O;
