function [beta_p_corr,bbp] = BB9cal(BB9data,DarkCounts,aAC,wvlAC,wvlBB9,Tc,S)
%% Function to calibrate raw data from the BB9 Wetlabs instrument.
% Convert the counts measurements to values of the VSF at one angle
% 9 bands for a 117 degrees angles and subtracts VSF of seawater
% by Javier A. Concha
% 07-23-13
%
%
wavelength = [407,439,485,507,527,594,651,715,878];
%% Calibration parameters
SF407 = 4.533E-05;%[m^(-1)sr^(-1)/counts]
SF439 = 1.999E-05;
SF485 = 1.946E-05;
SF507 = 1.615E-05;
SF527 = 1.682E-05;
SF594 = 1.047E-05;
SF651 = 9.738E-06;
SF715 = 8.375E-06;
SF878 = 6.404E-06;

data407 = (BB9data(:,1)-DarkCounts(1))*SF407;
data439 = (BB9data(:,2)-DarkCounts(2))*SF439;
data485 = (BB9data(:,3)-DarkCounts(3))*SF485;
data507 = (BB9data(:,4)-DarkCounts(4))*SF507;
data527 = (BB9data(:,5)-DarkCounts(5))*SF527;
data594 = (BB9data(:,6)-DarkCounts(6))*SF594;
data651 = (BB9data(:,7)-DarkCounts(7))*SF651;
data715 = (BB9data(:,8)-DarkCounts(8))*SF715;
data878 = (BB9data(:,9)-DarkCounts(9))*SF878;

BB9caldata = [data407 data439 data485 data507 data527 data594 ...
    data651 data715 data878];




switch nargin
    case 7 %% Sea water subtraction
        beta_thetap = zeros(size(BB9caldata));        
        for i =  1:size(BB9caldata,1)
            theta = 124; % degrees
            [betasw,~,~] = betasw_ZHH2009(wavelength,Tc(i),theta,S(i));
            beta_thetap(i,:) = BB9caldata(i,:)-betasw;
        end
        beta_p_corr = pathcorr(aAC,beta_thetap,wvlAC,wvlBB9);
        
    case 5
        beta_thetap = BB9caldata; 
        beta_p_corr = pathcorr(aAC,beta_thetap,wvlAC,wvlBB9);
        
    case 2
        beta_p_corr = BB9caldata; 
end



%% backscattering
X = interp1([120 130],[1.12 1.17],124); % interpolation from X table
bbp = 2*pi*X.*beta_p_corr;


function beta_p_corr = pathcorr(aAC,beta_thetap,wvlAC,wvlBB9)
%% Correct VSF for absorption along the path
% Convert AC-S data to BB9 wavelength

for i = size(aAC,1)
    aBB9(i,:) = interp1(wvlAC,aAC(i,:),wvlBB9);
end
L = 0.039; % length path
beta_p_corr = beta_thetap.*exp(L.*aBB9);



