function connrules_output=coloring_NCC_findrules(connrules, liblist, itarget, libs, threshold)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% General description:
%
% This function recursively finds forbidden pairs such that there is no 
% non-negative canoncial correlation with the itarget-th component that 
% is higher than threshold .
%
% input:
%       connrules - Forbidden pairs found so far
%       liblist - The range in the library to consider for avoiding high 
%                 non-negative canoncial correlation 
%       itarget - The spectrum to work on 
%       libs - The global spectrum library
%       threshold - A upper bound for non-negative canoncial correlation
%
% output: 
%       connrules_output - forbidden pairs found so far
%
% Written by: Wei Wang
% Machine Learning for Signal Processing Lab
% University of Maryland, Baltimore County
% 8/21/2007
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if length(liblist)==1
    connrules_output=connrules;
    return;
end

% Calculate non-negative canonical correlation with the current component
restlib=libs(:,liblist);
[A,B,r] = CCA_nonnegative(libs(:,itarget),restlib);

if r < threshold
    connrules_output=connrules;
    return;
end

BB=B;
[ss,iis]=sort(BB,'descend');

% The two components that contribute most form a forbidden pair
idleft=liblist(iis(1));
idright=liblist(iis(2));
connrules(idleft,idright)=1;
connrules(idright,idleft)=1;

% 
% sss=sprintf('target=%d, left=%d, right=%d, length_liblist=%d',itarget, ...
%     idleft,idright,length(liblist));
% disp(sss);
% s0=sprintf('%d ', liblist);
% disp(s0);

if(length(liblist)==2)
    connrules_output=connrules;
    return;
end
    

% Keep finding forbidden pairs in the range without both the ileft-th and 
% iright-th component
list2=liblist;
list2([iis(1) iis(2)])=[];
connrules=coloring_NCC_findrules(connrules,list2,itarget,libs,threshold);

% Keep finding forbidden pairs in the range without the ileft-th component
leftconn=connrules(idleft,:);
leftconnlist=find(leftconn==1);
[c,ia,ib]=intersect(liblist,leftconnlist);
liblistleft=liblist;
liblistleft(ia)=[];
% disp('left range:');
% s0=sprintf('%d ', liblistleft);
% disp(s0);
connrules=coloring_NCC_findrules(connrules,liblistleft,itarget,libs,threshold);

% Keep finding forbidden pairs in the range without the iright-th component
rightconn=connrules(idright,:);
rightconnlist=find(rightconn==1);
[c,ia,ib]=intersect(liblist,rightconnlist);
liblistright=liblist;
liblistright(ia)=[];
% disp('right range:');
% s0=sprintf('%d ', liblistright);
% disp(s0);
connrules_output=coloring_NCC_findrules(connrules,liblistright,itarget,libs,threshold);