function [outperm, rawindex, allperms, index] = ...
   pairwiseqa(prox, targ, inperm)

% PAIRWISEQA carries out an iterative Quadratic Assignment maximization task using the
% pairwise interchanges of objects in the permutation defining the row and column 
% order of the data matrix.
% INPERM is the input beginning permutation (a permuation of the first $n$ integers).
% PROX is the $n \times n$ input proximity matrix.
% TARG is the $n \times n$ input target matrix.
% OUTPERM is the final permutation of PROX with the cross-product index RAWINDEX
% with respect to TARG.
% ALLPERMS is a cell array containing INDEX entries corresponding to all the
% permutations identified in the optimization from ALLPERMS{1} = INPERM to 
% ALLPERMS{INDEX} = OUTPERM.

tic;
begindex = sum(sum(prox(inperm,inperm).*targ));
outperm = inperm;
nchange = 1;
n = length(inperm);
index = 1;
allperms{index} = inperm;

while (nchange == 1)
   
   nchange=0;
   
   for k = 1:(n-1)
      for j = (k+1):n
                   
         intrperm = outperm;
             
         intrperm(k) = outperm(j);
         intrperm(j) = outperm(k);
         
         tryindex = sum(sum(prox(intrperm,intrperm).*targ));
            
         if(tryindex > (begindex + 1.0e-008))
            nchange = 1;
            begindex = tryindex;
            outperm = intrperm;
            index = index + 1;
            allperms{index} = intrperm;
         end
         
      end
   end
end

rawindex = begindex;
toc