function [ IntVal ] = gIntegrate( I_Spec,yax,N,plots,varargin)
%% FUNCTION gIntegrate for integrate spectral data
% (C)DPG--
% Inputs:
% I_Spec=Specra of data to integrate
% yax=Axisscale of the spectra (e.g. wavenumbers)
% N=Order of polinomial to fit the baseline (e.g. 1= strightline)
% plots= If plot is guanted or not. 'y' if yes.
% varargin: Baselines points
% If = 1 Height of the point over 0 (Absorbance).
% If = 2 Integral between P1 and P2 over the 0 baseline.
% If = 4 

I_Spec=[I_Spec;mean(I_Spec)]; % last spectra is teh average for plots
switch size(varargin,2) 
    case 1
    P1=varargin{1};
    [tP]=gTranslator([P1 P1],yax);
    for i=1:size(I_Spec,1)
        Int=I_Spec(i,tP);
        IntVal(i)=Int;
    end
    case 2
    P1=varargin{1};
    P2=varargin{2}; 
    [tP]=gTranslator([P1 P2],yax);% REGION OF POINTS TO INTEGRATE
    for i=1:size(I_Spec,1);
        Int=trapz(I_Spec(i,tP));
        IntVal(i)=Int;
    end
    
%     case 3   CHECK FOR LATER
%     P1=varargin{1};
%     P2=varargin{2};
%     B1=varargin{3};
%     [tP]=gTranslator([P1 P2],yax);% REGION OF POINTS TO INTEGRATE
%     [tB1]=gTranslator([B1 B1],yax);% REGION OF POINTS OF BASELINE
%     
%     for i=1:size(I_Spec,1)
%         yTB1=(I_Spec(i,tB1));% Extract spectral region
%         bl=trapz(tP,(repmat(yTB1,length(tP),1)));% Calculate 
%         Int=trapz(I_Spec(i,tP));
%         IntVal(i)=Int-bl;
%     end
    
    case {4,5,6}
    P1=varargin{1};
    P2=varargin{2};
    B1=varargin{3};
    B2=varargin{4};  
    if size(varargin,2)==4 
    B3=B1;
    B4=B2;
    end
    if size(varargin,2)==5
    B3=varargin{5};
    B4=B2;
    end
    if size(varargin,2)==6
    B3=varargin{5};
    B4=varargin{6};
    end
    tic
        [tP]=gTranslator([P1 P2],yax);% REGION OF POINTS TO INTEGRATE
        [tB1]=gTranslator([B1 B2],yax);% REGION OF POINTS OF BASELINE 1
        [tB2]=gTranslator([B3 B4],yax);% REGION OF POINTS OF BASELINE 2      
        IntVal=(zeros(size(I_Spec,1),1)); 
        WB = waitbar(0,'INTEGRATING VALUES...WAIT');
        for i=1:size(I_Spec,1); 
            if sum(i/size(I_Spec,1)==[0.25:0.5:0.75])>0;
        waitbar(i/size(I_Spec,1));       % Check time
            end
        yTB1=(I_Spec(i,tB1));
        yTB2=(I_Spec(i,tB2));
        xTB1=(tB1);
        xTB2=(tB2);
        % Create Baseline Between B1 and B2
        ws = warning('off','all');
        p=polyfit_f([xTB1 xTB2],[yTB1 yTB2],N);
        warning(ws);
        y=polyval(p,tP);
        bl=trapz(y);
        Int=trapz(I_Spec(i,tP));
        IntVal(i)=Int-bl;
        end
        close (WB) ;

end

IntVal(end)=[];%TAke out the Average
%% NOTE PLOTS

if plots=='y'
Avspec=I_Spec(i,:);
figure
plot(yax,Avspec)
hold on
if size(varargin,2)>2
plot(yax(tB1),Avspec(:,tB1),'r')
plot(yax(tB2),Avspec(tB2),'r')
plot(yax(tP),Avspec(tP),'g')
plot(yax(tP),y,'k')
end



patch([yax(tP) flip(yax(tP))],[Avspec(1,tP) flip(y)],'g');
end
%bar(yax(tP),Avspec(1,tP),'g')
%if size(varargin,2)>2
%bar(yax(tP),y,'k')
%end
end

