function [Gain, Offset] = Gain_aircal(CTDTemperature,AtmosphericPressure,RelativeHumidity,OptodeReadingRAW)
% Calculate the gain of the SBE63 dissolved oxygen optode
% Inputs:
    % CTDTemperature: CTD temperature reading (Celsius)
    % RelativeHumidity: Relative humidity of air during calibration (fractional)
    % OptodeReadingRAW: Raw SBE63 doxy sensor output (mL/L)
    % AtmosphericPressure: Barometer reading during calibration (mbar)
% Intermediates:
    
    % Ts: Scaled temperature (Garcia and Gordon 1992, Bittig 2018). 
    % This is a data transformation to improve the RMS of the fit.

    
% Output:
    % Gain: The ratio of the 'true' value to the measured value. 
    % Over time, the sensor will drift from the factory calibration and
    % will need this additional step to the correct the data.
    % Offset: If there is calibration data for the zero saturation point,
    % the offset (or y-intercept) of the correction can also be calculated.
    % This further decreases the error in the resulting data and is best
    % practice.
    
    A0​ = -173.4292;
    A1 = 249.6339;
    A2 = 143.3483;
    A3 = -21.8492;
    A4 = -1.7876​;
    A5 = 0.0008526;
    
    A = 52.57;
    B = 6690.9;
    C = 4.681;
    
    Pr = 1; % atm
    Pa = AtmosphericPressure;

    pH20 = exp(A - (B / (CTDTemperature + 273.15)) - C * log(CTDTemperature + 273.15));
    Rh = RelativeHumidity;
    
    
    Pf = ((Pa - pH20*Rh)*(Pr - Theta0*Pa)) / ((Pr - pH20*Rh)*(Pr - Theta0*Pr));
    Ts = log((298.15 - CTDTemperature) / (273.15 + CTDTemperature));
    O2_TS = exp(A0 + A1*Ts + A2*Ts^2 + A3*Ts^3 + A4*Ts^4 + A5*Ts^5);

    O2_TSP = O2_Ts * Pf;


end

