%
% This function is from Jim Bellingham's cCTD_sal.m with heavy modification.
% The function computes salinity with corrections and then density.
% correction parameters from LagModel will be passed. See cCTD_sal.m for 
% other info.
% return [sal dens...] if k is found in correct_linear.dat, return [] if not
%
% Major change: use original time grids instead evenly spaced grids, so no 
% need to modify other scripts
% 
% Xuri Yu
% August 4, 1999
%

function sal = cal_sal(time,temp,cond,press,pitch,k)
 
% linearly interpolate data and add time lag to conductivity
ok = find(~isnan(temp));
ctd_temp = interp1q(time(ok),temp(ok),time);

% Add lag to conductivity
ok = find(~isnan(cond));
cond = interp1q(time(ok),cond(ok),time-k(1));

%  Convert bar to decibars and make depth correction for AUV attitude
ok = find(~isnan(press));
ctd_pres = interp1q(time(ok),cCTD_pres(press(ok),pitch(ok)),time);

% -----------------------------------------------------------------------
% Compute the temperature of the conductivity cell...

cell_tau = k(2);   % time constant of cell...
cell_temp = ctd_temp;
g = exp(-diff(time)/cell_tau);  % integration kernel

for indx = 2:length(time),
   cell_temp(indx) = g(indx-1)*cell_temp(indx-1) + (1-g(indx-1))*ctd_temp(indx);
end

% -----------------------------------------------------------------------
% Compute the corrected water temperature at the conductivity cell

fcond = k(3);
cond_temp = ctd_temp - fcond * (ctd_temp - cell_temp);

% -----------------------------------------------------------------------
% Compute the salinity, density, depth, and sos...

sal = sw_salt(10*cond/sw_c3515,cond_temp,10*ctd_pres);

%ctd_dens = sw_dens(ctd_salt, ctd_temp, 10*ctd_pres);
%ctd_depth = sw_dpth(10*ctd_pres, 42);   % Use latitude of MA Bay....
%ctd_sos = sw_svel(ctd_salt, ctd_temp, 10*ctd_pres);

return
