%CTD_Freq_Conv      Calculate temperature and conductivity.
%
%   [TEMP,COND] = O2_CTPC( PRESSURE, COND, TEMP, IDSTR ) takes raw sensor
%   values pressure (bar), conductivity frequency output (hz), and
%   temperature frequency output (hz) and returns temperature (deg C),
%   conductivity (S/m).  
%
%   First option for IDSTR is 'night'. This specifies the calibration 
%   coefficients of the SBE CTD instrumentation on board the Odyssey II 
%   'biolum' vehicle used during the MUSE experiment.
%
%		temp sensor:  serial # 2819  calibration 11-Nov-99
%     cond sensor:  serial # 2258  calibration 22-Oct-99
%
%   Second option for ISDR is 'old_day'.  This specifies the temperature
%   and conductivity sensors used on the 'day' AUV through August 27th.
%
%		temp sensor:  serial # 2813  calibration 26-Feb-00
%     cond sensor:  serial # 2405  calibration 07-Feb-00
%
%   Revision of Haro Strait era CTD conversion routine.  Modified to 
%   handle data taken by the 'night' or 'biolum' vehicle during the 
%   MUSE experiment (also called AOSN 2000).  Runs on the 25th and 26th 
%   used an incorrect calibration.
%
%   Jim Bellingham, MBARI
%   August 27, 
%----------------------------------------------------------------------


function [temp,cond,mask] = ctd_freq_conv( mpres, mcond_hz, mtemp_hz, idstr )

if ( nargin < 4 )
   errormsg( 'missing identification string' );
end

if (strcmp( idstr, 'night' ) == 1)
   temp_a = 3.67997127e-3;
   temp_b = 6.01240767e-4;
   temp_c = 1.58748231e-5;
   temp_d = 2.03516651e-6;
   temp_f0 = 3039.622;
   
   cond_a = 2.85475358e-22;
   cond_b = 1.56709467e00;
   cond_c = -1.06453205e1;
   cond_d = -1.09885720e-5;
   cond_m = 23.7;
   eps = -9.57e-08;
elseif 'old_day'
   temp_a = 3.67999722e-3;
   temp_b = 6.02624547e-4;
   temp_c = 1.59294960e-5;
   temp_d = 2.06238399e-6;
   temp_f0 = 2798.583;
   
   cond_a = 2.80551784e-4;
   cond_b = 1.59349759e0;
   cond_c = -1.09374861e1;
   cond_d = -8.48450433e-5;
   cond_m = 3.5;
   eps = -9.57e-08;
else
   return;
end;

% First do temp conversion

mask = find( mpres > 0.15 & finite(mtemp_hz) & mcond_hz > 3500 );

temp = NaN*zeros(size(mtemp_hz));
temp(mask) = -273.15 + 1 ./ polyval([temp_d temp_c temp_b temp_a], ...
   log(temp_f0./mtemp_hz(mask)));

% Now do the conductivity conversion

if nargout > 1
   
   pdbar = 10*mpres(mask);
   cond_khz = 0.001*mcond_hz(mask);
   
   cond = NaN*zeros(size(mcond_hz));
   cond(mask) = (cond_a*cond_khz.^cond_m + cond_b*cond_khz.^2 + ...
      cond_c + cond_d*temp(mask))./(10*(1 + eps*pdbar));
end
