
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% General description:
%
% This function find corresponding background for the observation data
%
%
% input:
%       dataNB - observation data
%       backgrounds - extracted background array
%       wavel - wavenumber 
%
% output: 
%       output - index of the corresponding background component
%
% Written by: Wei Wang
% Machine Learning for Signal Processing Lab
% University of Maryland, Baltimore County
% 9/22/2007
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output]=JCSD_background_matching(dataNB, backgrounds, wavel)

yNB0=mean(dataNB,2);
[posNB, ampsNB, yNB, y_smoothed]=extracting_peaks(yNB0',wavel);   
locsNB=wavel(posNB);
m=size(backgrounds,2);
dt=30;
for i=1:m
    tBkg0=backgrounds(:,i);
    [posBkg, ampsBkg, yBkg, y_smoothed]=extracting_peaks(tBkg0',wavel);
    locsBkg=wavel(posBkg);
    [locsData,idA,idB, ampsNB_all, ampsBkg_all] ...
        = union_peaks(locsNB, locsBkg, ampsNB, ampsBkg, dt);
    cors(i)=corr2(ampsNB_all,ampsBkg_all);
        
end

pid=find(cors==max(cors));
output=pid(1);