
function sal = calcSal(C,temp,press)

% -- 
% Jeff Sevadjian
% Research Technician
% Monterey Bay Aquarium Research Institute
% 7700 Sandholdt Rd
% Moss Landing, CA 95039, USA
% ph: +1 831-775-1888

% Calculates salinity from conductivity, temperature, and pressure.
%  Code is also included to calculate conductivity from a SeaBird CTD's
%  raw conductivity frequency.

% http://www.seabird.com/application_notes/AN14.htm
% Results are identical (within 10^-15) to UNESCO algorithm

%--%

% %Sample code to calculate conductivity [S/m] from raw conductivity
%  frequency:
% 
% %calibration coefficients S/N 4458 (20-Dec 2011)
%  g = -1.031365e0;
%  h = 1.415565e-1;
%  i = -2.458798e-4;
%  j = 3.914370e-5;
%  CTcor = 3.25e-6;
%  CPcor = -9.57e-8;
% 
% %coefficients
%  f = C/1000; %C is sensor frequency (not conductivity)
%  
% %calculate conductivity
%  Cond = (g + h*f.^2 + i*f.^3 + j*f.^4) ./ ...
%    (1 + CTcor*temp + CPcor*press); %(S/m)

%--%

 Cond = C;

%convert temp (ITS-90) to temp (IPTS-68)
 temp = 1.00024*temp;

%convert conductivity (S/m) to salinity (psu)

 %coefficients
  A1 = 2.07e-5;
  A2 = -6.37e-10;
  A3 = 3.989e-15;
  B1 = 3.426e-2;
  B2 = 4.464e-4;
  B3 = 4.215e-1;
  B4 = -3.107e-3;
  c0 = 6.766097e-1;
  c1 = 2.00564e-2;
  c2 = 1.104259e-4;
  c3 = -6.9698e-7;
  c4 = 1.0031e-9;
  a = [0.008 -0.1692 25.3851 14.0941 -7.0261 2.7081];
  b = [0.0005 -0.0056 -0.0066 -0.0375 0.0636 -0.0144];
  k = 0.0162;

 %calculation
  R = Cond*10/42.914;
  Rp = 1 + ( press.*(A1 + A2*press + A3*(press.^2)) ) ./ ...
    (1 + B1*temp + B2*(temp.^2) + B3*R + B4*R.*temp);
  rT = c0 + c1*temp + c2*(temp.^2) + c3*(temp.^3) + c4*(temp.^4);
  RT = R./(Rp.*rT);
  sum1 = 0;
  sum2 = 0;
  for n=1:length(a)
    sum1 = sum1+a(n)*(RT.^((n-1)/2));
    sum2 = sum2+b(n)*(RT.^((n-1)/2));
  end
  
  sal = real( sum1 + ((temp-15).*sum2) ./ (1 + (k*(temp-15))) );
