function dist=txtursim(x,r_xx,N_T,Measure,M_h,N_h)
% TXTURSIM  Compute texture similarity measure between several textures
%	dist=txtursim([],[r_xx1;r_xx2;...;r_xxn],n,'AG',M_h,N_h) 
%	computes the 1-arithmetic to geometric mean texture dimilerity
%	measure between the n textures given by their autocorrelation 
%	functions, i.e.
%	                  AritmeticMean(R_xx2^(-1)*R_xx1)
%	    dist(i,j)=1 - -------------------------------
%	                  GeometricMean(R_xx2^(-1)*R_xx1)
%	
%	For a 7x7 filter, it is empirically fount that for the AG measure
%	 - dist(i,j)<0.04 => textures x_i and x_j are vergy similar
%	 - dist(i,j)>0.4  => textures x_i and x_j are vergy dissimilar
%	 
%	Alternatives to the 'AG' measure are the 'Singh' and 'Unser'
%	measures, using the criterion functions for the optimal filter.


[M_r,N_r]=size(r_xx);
M_r=M_r/N_T;

dist=[];
for i=1:N_T-1
  R_xxA=r2R(r_xx((i-1)*M_r+1:i*M_r,:),M_h,N_h);
  inv_R_xxA=inv(R_xxA);
  for j=i+1:N_T
    R_xxB=r2R(r_xx((j-1)*M_r+1:j*M_r,:),M_h,N_h);
    [H,D]=eig(inv_R_xxA*R_xxB);
    lambda= diag(D)';
    if strcmp(lower(Measure),'unser')
      J=lambda+lambda.^(-1)-2;
      dist(i,j)=max(J(:));
    elseif strcmp(lower(Measure),'singh')
      J=lambda;
      dist(i,j)=max(J(:));
    elseif strcmp(lower(Measure),'ag')
      dist(i,j) = mean(lambda)/geomean(lambda);
    else
      error(sprintf('Unknown measure "%s"',Measure));
    end
    dist(j,i) = dist(i,j);
  end
end
