function [gcoordsort, gperm] = ...
   guttorder(prox,inperm)

%GUTTORDER carries out a unidimensional scaling of a symmetric proximity
%  matrix using Guttman's updating algorithm.
%  PROX is the input proximity matrix (with a zero main diagonal and a
%  dissimilarity interpretation);
%  INPERM is an input permutation of the first $n$ integers;
%  GCOORDSORT are the coordinates ordered from most negative to most positive;
%  GPERM is the object permutation that indicates which objects are at which of the
%  ordered coordinates in GCOORDSORT.

n = size(prox,1);
gpermprev = inperm;
gcoord = zeros(n,1);
gcoordprev = zeros(n,1);

for i = 1:n
   for j = 1:n
      if(inperm(j) == i)
         gcoordprev(i) = j;
      end
   end
end

         

for i = 1:n
   for j = 1:n
      gcoord(i) = gcoord(i) + (prox(i,j)*sign(gcoordprev(i) - ...
         gcoordprev(j)))/n;
   end
end


gperm = 1:n;
gcoordsort = gcoord;

for i = 1:(n-1)
   for j = (i+1):n
      if(gcoordsort(i) > gcoordsort(j))
         tempcoord = gcoordsort(i);
         gcoordsort(i) = gcoordsort(j);
         gcoordsort(j) = tempcoord;
         tempperm = gperm(i);
         gperm(i) = gperm(j);
         gperm(j) = tempperm;
      end
   end
end


while(any(gpermprev - gperm) == 1) 
   gcoordprev = gcoord;
   gpermprev = gperm;
   gcoord = zeros(n,1);   
   for i = 1:n
      for j = 1:n
         gcoord(i) = gcoord(i) + (prox(i,j)*sign(gcoordprev(i) - ...
            gcoordprev(j)))/n;
      end
   end
   
  
  gperm = 1:n;
  gcoordsort = gcoord;

   for i = 1:(n-1)
      for j = (i+1):n
         if(gcoordsort(i) > gcoordsort(j))
            tempcoord = gcoordsort(i);
            gcoordsort(i) = gcoordsort(j);
            gcoordsort(j) = tempcoord;
            tempperm = gperm(i);
            gperm(i) = gperm(j);
            gperm(j) = tempperm;
         end
      end
   end
 

end
