function S = conductivity2salinity(R,T,P)
%conductivity2salinity
%
%   S = siltprofiler_conductivity2salinity(R,T,P)
%
% converts conductivity C to salinity S using p[res P and temp T.

% INPUT: 
%   T = temperature [degree C (IPTS-68)]
%   P = Pressure [cm]
%   R = Conductivity [mS/cm]

% From:
%    Unesco 1983. Algorithms for computation of fundamental properties of 
%    seawater, 1983.


%%
% check input

if nargin ~=3
   error('conductivity2salinity must pass 3 parameters')
end %if

[mR,nR] = size(R);
[mT,nT] = size(T);
[mP,nP] = size(P);

if (mR~=mT) | (nR~=nT)
   error('R,T inputs must have the same dimensions')
end


  R = R(:)./42.9140;
  T = T(:);
  P = P(:)./100;



  
%%
% Calculate rt

c0   =  0.6766097;
c1   =  2.00564e-2;
c2   =  1.104259e-4;
c3   = -6.9698e-7;
c4   =  1.0031e-9;

rt = c0 + (c1 + (c2 + (c3 + c4.*T).*T).*T).*T;

%%
% Calculate Rp
d1 =  3.426e-2;
d2 =  4.464e-4;
d3 =  4.215e-1;
d4 = -3.107e-3;

e1 =  2.070e-5;
e2 = -6.370e-10;
e3 =  3.989e-15;

Rp = 1 + ( P.*(e1 + e2.*P + e3.*P.^2) ) ...
     ./ (1 + d1.*T + d2.*T.^2 +(d3 + d4.*T).*R);
 
%%
% Calculate (capital) Rt

Rt = R./(Rp.*rt);



%%
% Calculate Salinity

a0 =  0.0080;
a1 = -0.1692;
a2 = 25.3851;
a3 = 14.0941;
a4 = -7.0261;
a5 =  2.7081;

b0 =  0.0005;
b1 = -0.0056;
b2 = -0.0066;
b3 = -0.0375;
b4 =  0.0636;
b5 = -0.0144;

k  =  0.0162;

Rtx   = sqrt(Rt);
del_T = T - 15;
del_S = (del_T ./ (1+k*del_T) ) .* ...
        ( b0 + (b1 + (b2+ (b3 + (b4 + b5.*Rtx).*Rtx).*Rtx).*Rtx).*Rtx);
	
S = a0 + (a1 + (a2 + (a3 + (a4 + a5.*Rtx).*Rtx).*Rtx).*Rtx).*Rtx;

S = S + del_S;
%--------------------------------------------------------------------
			