function [find,vaf,outperm,rowperm,colperm,addcon,coord] =  ...
    ms_uniscaltmac(proxtm,inperm,kblock,addcontol,maxiteration)

% UNISCALTMAC finds and fits a linear 
% unidimensional scale using iterative projection to
% a two-mode proximity matrix in the $L_{2}$-norm based on a 
% permutation identified through the use of iterative 
% quadratic assignment.
%
% syntax: [find,vaf,outperm,rowperm,colperm,addcon,coord] = ...
%    uniscaltmac(proxtm,inperm,kblock)
%
% PROXTM is the input two-mode proximity matrix 
% ($n_{a} \times n_{b}$ with a zero main diagonal
% and a dissimilarity interpretation);
% INPERM is a given starting permutation of the 
% first $n = n_{a} + n_{b}$ integers;
% FIND is the least-squares optimal matrix (with 
% variance-accounted-for of VAF) to PROXTM having a linear
% unidimensional form for the row and column
% object ordering given by the ending permutation OUTPERM.
% The spacings among the objects are given by the entries in FIND.
% KBLOCK defines the block size in the use of the iterative 
% quadratic assignment routine.
% The additive constant for the model is given by ADDCON.
% ROWPERM and COLPERM are the resulting row and column 
% permutations for the objects.  The nrow + ncol coordinates
% (ordered with the smallest set at a value of zero) 
% are given in COORD.

[nrow ncol] = size(proxtm);



n = nrow + ncol;
targrenew = zeros(n,n);

targlinear = targlin(n);

%addcontol = 1.0e-005;
%maxiteration = 1000;
invar = zeros(2,1);


[outperm,rawindex,index,squareprox] =  ms_ordertm(proxtm,targlinear,inperm,kblock);

rowdum = zeros(nrow,1);
coldum = zeros(ncol,1);
dumone = zeros(1,1);

[find,coord,outvar] = ms_linfittmac(proxtm,outperm,invar,addcontol,maxiteration);

vaf = outvar(1);
addcon = outvar(2);


 rowperm = zeros(nrow,1);
   colperm = zeros(ncol,1);
   colidx = 0;
   rowidx = 0;
   
   for i = 1:n
      
      if (inperm(i) <= nrow)
         
         rowidx = rowidx + 1;
        rowperm(rowidx) = inperm(i);
      end
         
      if (inperm(i) > nrow)
         
         colidx = colidx + 1;
         colperm(colidx) = inperm(i) - nrow;
         
      end
   end

if (any(outperm-inperm) ~= 0)
    
    for i = 1:n
        for j =1:n
            targrenew(i,j) = abs(coord(i) - coord(j));
        end
    end
    
    inperm = outperm;
    [outperm,rawindex,index,squareprox] = ms_ordertm(proxtm,targrenew,inperm,kblock);
    [find,coord,outvar] = ms_linfittmac(proxtm,outperm,invar,addcontol,maxiteration);
   
    vaf = outvar(1);
    addcon = outvar(2);
end

 rowperm = zeros(nrow,1);
   colperm = zeros(ncol,1);
   colidx = 0;
   rowidx = 0;
   
   for i = 1:n
      
      if (inperm(i) <= nrow)
         
         rowidx = rowidx + 1;
        rowperm(rowidx) = inperm(i);
      end
         
      if (inperm(i) > nrow)
         
         colidx = colidx + 1;
         colperm(colidx) = inperm(i) - nrow;
         
      end
   end