%%*********************************************************************
%% sortA: sort columns of Avec{p} in ascending order according to the 
%%        number of nonzero elements. 
%%
%% [Avec,C,X0,Z0,permA,permZ] = sortA(blk,Avec,C,X0,Z0);
%%
%% SDPT3: version 3.0 
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01 
%%*********************************************************************

   function [Avec,C,X0,Z0,permA,permZ] = sortA(blk,Avec,C,X0,Z0);

   global spdensity 
%%
   numblk = size(blk,1); m = size(Avec{1},2); 
   nnzA = zeros(numblk,m); permA = zeros(numblk,m); permZ = cell(size(blk,1),1);
   for p=1:size(blk,1)
      pblk = blk(p,:); 
      n = sum(pblk{2}); 
      numblk = length(pblk{2}); 
      if strcmp(pblk{1},'s');
         n2 = sum(pblk{2}.*pblk{2});  n22 = sum(pblk{2}.*(pblk{2}+1))/2; 
         if (length(pblk{2}) == 1);  
            tmp = abs(C{p})+abs(Z0{p})+smat(blk(p,:),abs(Avec{p}*ones(m,1)),1);
            if (nnz(tmp) < spdensity*n22); 
                per = symmmd(tmp);    
                permZ{p} = spconvert([ [1:n]' per' ones(n,1) ]);    
                isspAvec = issparse(Avec{p});
                for k = 1:m
                   Ak = smat(pblk,Avec{p}(:,k),1); 
                   Avec{p}(:,k) = svec(pblk,Ak(per,per),isspAvec); 
                end
                C{p}  = C{p}(per,per);   
                X0{p} = X0{p}(per,per);         
                Z0{p} = Z0{p}(per,per); 
            end; 
         end
         for k = 1:m
            Ak = Avec{p}(:,k); 
            nnzA(p,k) = length(find(abs(Ak) > eps)); 
         end; 
         [dummy,permAp] = sort(nnzA(p,:)); 
         Avec{p}  = Avec{p}(:,permAp); 
         permA(p,:) = permAp;  
      elseif strcmp(pblk{1},'q') | strcmp(pblk{1},'l'); 
         permA(p,:) = [1:m]; 
         if ~issparse(Avec{p}); 
            Avec{p} = sparse(Avec{p}); 
         end
      end;
   end;
%%*********************************************************************
