function [PotSetsHierarchy,PotSetsMetric,PotSets]=gkreduc2(PotNodes,PotNodesMetric,PotNodesPartition,Treshold,m,data,aexp,bexp);
% Reduction of the number of clusters
% 
% Syntax:
%
% [ClusSetsHierarchy,ClusSetsMetric,ClusSets]=gkreduc(Centers,Variances,Partition,Threshold,m,data,aexp,bexp)
%
% Inputs:
% 
% Centers is a k*n matrix containing the centers of the clusters [c1 c2 c3 ... cn]
% Variances is a k*(n.k) matrix containing the variances of the clusters [s1 s2 s3 ... sn]
% Partition is a n*N matrix containing the membership degrees of each vector to each cluster
% Threshold is the minimal number of clusters
% m is scalar representing the fuzziness of the partition
% data is a k*N matrix
% aexp is a scalar representing the relative importance of the proximity criterion
% bexp is a scalar representing the relative importance of the size criterion
%
% Outputs:
%
% ClusSetsHierarchy is a matrix containing the hierarchy relationships between the clusters
% ClusSetsMetric is a matrix containing the variances of the merged clusters
% ClusSets is a matrix containing the centers of the merged clusters

if (nargin < 7), aexp = 1;    elseif isempty(m),   aexp = 1; end;
if (nargin < 8), bexp = 3;    elseif isempty(m),   bexp = 3; end;
if (nargin < 9), cexp = 2;    elseif isempty(m),   cexp = 2; end;

dimension=size(PotNodes,1);
numrules=size(PotNodes,2);
PotSetsHierarchy=[];
PotSets=[];
PotSetsMetric=[];
Limit=0;

crit=1;
while ((numrules>Treshold))
  [SecondSetsMetrics,SecondSets,IDs]=get1lev(PotSetsHierarchy,PotSetsMetric,PotSets,PotNodesMetric,PotNodes);
  
  % S1 tient compte de la proximite
  S1=zeros(size(SecondSets,2));
  for i=1:size(SecondSets,2),
    Psi=SecondSets(1:end-1,i)*ones(1,size(SecondSets,2));
    S1(i,:)=sum((Psi-SecondSets(1:end-1,:)).^2,1);
  end;
  S1=triu(sqrt(S1));
  S1=S1/max(max(S1));
  
  % Compute the sizes differences
  w=ones(1,size(SecondSets,2));
  for i=1:size(SecondSets,2),
  	w(i)=clusWeight(PotSetsHierarchy,IDs(i));
  end
  
  S2=zeros(size(SecondSets,2));
  for i=1:size(SecondSets,2),
    Psi=w(i)*ones(1,size(SecondSets,2));
    S2(i,:)=(Psi-w).^2;
  end;
  S2=triu(sqrt(S2));
  
  
  [MinColS123,iTable]=min(S1+S2/4+1e9*(S1==0));
  [MinLineS123,j]=min(MinColS123);
  
  i=iTable(j);
  % If S123=0, on peut se retrouver avec l'element 1 1
  if ~(i==j),
    numrules=numrules-1;
    [PotSetsHierarchy,PotSetsMetric,PotSets]=gkmerge(PotNodes,PotNodesMetric,PotNodesPartition,...
	PotSetsHierarchy,PotSetsMetric,PotSets,i,j,IDs,m,data);
  end
  
end
