
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% General description:
%
% This function performs DCCP detection 
%
% input:
%       x - input data
%       libs - library spectra
%       wavel - wavenumber
%       clusters - library partitions
%       list_corr_spectra - list of pairs with correlation 
%         greater than threshold. The firt column is indices of components 
%         that have been removed from the library. The second column is the
%         indices of components that are kept. 
%         In detection, when a component whose index is in the second column
%         appears, a second stage classification is performed to identify
%         the target between this component and its counterpart.
% output: 
%       cc - DCCP scores
%       cvid - target index detected by DCCP
%
% Written by: Wei Wang
% Machine Learning for Signal Processing Lab
% University of Maryland, Baltimore County
% 8/21/2007
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [cc,cvid]=JCSD_detector_DCCP(x,libs,wavel,clusters, list_corr_pairs)

% 
% [posPeaks, ampsPeaks, yy, y_smoothed]=extracting_peaks(mean(x,2)',wavel);   
% baseline=y_smoothed-yy;
% x=x-baseline'*ones(1,size(x,2));

% Remove sigularity
while rank(x)~=size(x,2)
    x=x(:,1:end-1);
end

% Both are column vectors
[numclusters,n]=size(clusters);
BB=zeros(numclusters,n);
for j=1:numclusters
    icount(j)=length(find(clusters(j,:)>0));
    cp=libs(:,clusters(j,1:icount(j)));     
    [A,B,r1] = canoncorr(x,cp);
    
    
    rr(j)=r1(1);
    
    BB(j,1:icount(j))=B(:,1)';
end

cc=max(rr);
pos=find(rr==cc);
if length(pos)~=1
    error('Two clusters having maximum canonical correlation! Take a look here!!');
end
ic=pos(1); % the cluster that target belongs to
cvs=abs(BB(ic,:));
pos2=find(cvs==max(cvs));
cvid=clusters(ic,pos2(1));

rrs=sort(rr,'descend');
dt=rrs(1)-rrs(2);
DistC=dt/std(rrs(2:end));


% If spectrum in high correlated list is found, then perform the second
% stage indentification
if ismember(cvid,list_corr_pairs(:,2))
    tp=find(list_corr_pairs(:,2)==cvid);
    list1=list_corr_pairs(:,1);    
    [cc,cvid]=JCSD_detector_2ndstage(x,libs,cvid,list1(tp));
end