function [ClusterA,ClusterB]=hier2pairclst(Clusters)
% HIER2PAICLST  Transform a hierachical clustering to pairwise clusters
%	[ClusterA,ClusterB]=hier2pairclst(Clusters) transforms Clusters,
%	presumably made by HIERCLST, to a set of cluster pairs, suitable for
%	optimal filter design.

ClusterA=[];
ClusterB=[];

% Form cluster pairs on this level
Clustering=Clusters(1,:);
for i=1:max(Clustering)-1
  i_idx=find(Clustering==i);
  for j=i+1:max(Clustering)
    j_idx=find(Clustering==j);
    ClusterA(size(ClusterA,1)+1,1:length(i_idx))=i_idx;
    ClusterB(size(ClusterB,1)+1,1:length(j_idx))=j_idx;
  end
end

% Hierarchically recurse to subgroups
if size(Clusters,1)>1
  for i=1:max(Clustering)
    idx=find(Clustering==i); 
    [ClusterAA,ClusterBB]=hier2pairclst(Clusters(2:size(Clusters,1),idx));
    % Transform the sub-cluster numbers back to the mother cluster range
    if ~isempty([ClusterAA ClusterBB])
      ClusterAA(find(ClusterAA))=idx(nonzero(ClusterAA));
      ClusterBB(find(ClusterBB))=idx(nonzero(ClusterBB));
      % Add the new cluster pairs to the overall cluster pair datasets
      ClusterA(size(ClusterA,1)+1:size(ClusterA,1)+size(ClusterAA,1),...
	1:size(ClusterAA,2)) = ClusterAA;
      ClusterB(size(ClusterB,1)+1:size(ClusterB,1)+size(ClusterBB,1),...
	1:size(ClusterBB,2)) = ClusterBB;
    end
  end
end
