function [D1, D2, As, err] = buScaleBunch(A)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% [D1, D2, As, err] = buScaleBunch(A)
% A can be symm or nonsym.
% if A is sym, Bunch's algorithm is called.
% if A is nonsym, Bunch's algorithm is called with [0, A; A', 0]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calls Bunch's algorithm for equilibration of sym matrices
%     in inf-norm, J Bunch, Equilibration of Symmetric matrices
%     in the max-norm, J. ACM 18(4), pp.566--572, 1971.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% by  Daniel Ruiz and Bora Ucar, 
% references: A symmetry preserving algorithm for matrix scaling
%             Daniel Ruiz and Bora Ucar
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

isSym = 1;
B = A;
[orgm, orgn] = size(A);
if(norm(A-A', inf)~= 0),
    m = orgm; n=orgn;
    B = [sparse(m,n), A;A', sparse(n,n)];
    isSym = 0;
end

%B is symmetric
DB = scalebunch( B );
if(isSym == 1),
    D1 = DB(1:end);
    D2 = D1;
else
    D1 = DB(1:orgm);
    D2 = DB(orgm+1:end);
end

As = buScale(A, D1, D2);

rows = max(abs(As));
cols = max(abs(As'));

errR = max(abs(rows - ones(size(rows))));
errC = max(abs(cols - ones(size(cols))));
err  = max(errR,errC);
