
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% General description:
%
% This function extracts peaks and performs baseline corrrection 
%
% input:
%       x - wavelnumber
%       y - spectrum
%
% output: 
%       locs - peak locations
%       amps - amplitudes of peaks
%       y_smoothed - smoothed spectrum
%       yy - smoothed spectrum after baseline correction
%
% Written by: Wei Wang
% Machine Learning for Signal Processing Lab
% University of Maryland, Baltimore County
% 8/21/2006
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [locs, amps,yy, y_smoothed]=extracting_peaks(y,x)

%% smoothing spectrum using wavelet filter
cutpt=0.15;
norder=30;
%y_smoothed=smooth_FIR2(y, norder, cutpt);
if length(y)<512 
    L=9;
else
    L=10;
end
y_smoothed = smooth_wavelet(y, 6, 1, L);


% varnoise=get_noise_variance_in_blank_range(y,y_smoothed, x);
varnoise=0;
peak_locs=find_peaks(y_smoothed,varnoise);
if length(peak_locs)==0
    locs=[];
    amps=0;
    yy=y;
    y_smoothed=y;
    return;
end

%baseline correction
yy=baseline_correction(peak_locs, y_smoothed);


locs=find_peaks(yy, varnoise);
amps=yy(locs);

plotflag=0;
%% display in figure
if plotflag==1    
s1=sprintf('FIR order=%d, cutpt=%2.1f',norder,cutpt);
stitle=s1;
figure; hold on;
plot(x,y,'r',x,y_smoothed,'b');
legend('raw spectrum','smoothed spectrum');
plot(x(peak_locs),y_smoothed(peak_locs),'o');
title(stitle); grid on;
loc1=peak_locs(1);
plot([x(loc1) x(loc1)+50],[y_smoothed(loc1) y_smoothed(loc1)+50*tslope*length(x)/(max(x)-min(x))],'LineWidth',3);

%s2=sprintf('medfilt width=%d',win_width);
% stitle=strcat(s1,', ',s2);
% stitle=s1;
% figure; hold on;
% plot(x,y,'r',x,y_smoothed,'b',x,bl,'m',x,yy,'y');
% legend('raw spectrum','smoothed spectrum','baseline','processed spectrum');
% plot(x(peak_locs),yy(peak_locs),'o');
% title(stitle); grid on;
% loc1=peak_locs(1);
% plot([x(loc1) x(loc1)+50],[yy(loc1)
% yy(loc1)+50*tslope*length(x)/(max(x)-min(x))],'LineWidth',3);
end
