function [error] = corTsgLinear(hMainFig, dateMin, dateMax)
% Correct the TSG salinity time series with the Water sample.
% Use a linear fit to the water sample/tsg difference
% 
% Input
% hMainFig ..... Handle to the main GUI
% dateMin ...... the correction is applied between dateMin and date Max
% dateMax ...... the correction is applied between dateMin and date Max
%
% Output
% Error ........  1 everything OK
%       ........ -1 dateMax <= date Min

% Get application data
% --------------------
tsg    = getappdata( hMainFig, 'tsg_data');
sample = getappdata( hMainFig, 'sample');

% Get PROBABLY_GOOD, PROBABLY_BAD and VALUE_CHANGED codes
% -------------------------------------------------------
PROBABLY_GOOD = get(tsg.qc.hash, 'PROBABLY_GOOD', 'code');
PROBABLY_BAD  = get(tsg.qc.hash, 'PROBABLY_BAD', 'code');
VALUE_CHANGED = get(tsg.qc.hash, 'VALUE_CHANGED', 'code');

if dateMax > dateMin
  
  % Find samples within TIME_WINDOWS with Good and probably Good QC
  % ---------------------------------------------------------------
  ind = find( sample.DAYD    >= dateMin &  sample.DAYD    <= dateMax &...
              sample.SSPS_QC <= PROBABLY_GOOD);

  if ~isempty(ind)

    % detect NaN in sample.SSPS_DIF due to bad QC code for tsg.SSPS
    % -------------------------------------------------------------
    ind2 = find(~isnan(sample.SSPS_DIF(ind)));

    % Compute linear fit of the TSG/SAMPLE difference
    % -----------------------------------------------
    if ~isempty(sample.SSPS_DIF(ind(ind2)))

      X = sample.DAYD(ind(ind2));
      Y = sample.SSPS_DIF(ind(ind2));

      [p, S, mu] = polyfit( X, Y, 1);

      % The correction is applied to the TSG between dateMin and dateMax using
      % a linear interpolation only on measurements with GOOD and
      % PROBABLY_GOOD QC
      % ----------------------------------------------------------------------
      dtTsg = find( tsg.DAYD    >= dateMin  & tsg.DAYD <= dateMax &...
        tsg.SSPS_QC <= PROBABLY_GOOD);

      [tsg.SSPS_ADJUSTED(dtTsg), tsg.SSPS_ADJUSTED_ERROR(dtTsg)] =...
                                            polyval( p, tsg.DAYD(dtTsg), S, mu);
      tsg.SSPS_ADJUSTED(dtTsg) = tsg.SSPS(dtTsg) + tsg.SSPS_ADJUSTED(dtTsg);
      
      % VALUE_CHANGED code
      % ------------------
      tsg.SSPS_ADJUSTED_QC(dtTsg)    = VALUE_CHANGED;
    end

  else

    % RAZ if no correction
    % --------------------
    dtTsg = find(tsg.DAYD >= dateMin & tsg.DAYD <= dateMax);

    tsg.SSPS_ADJUSTED(dtTsg)       = NaN*ones(size(tsg.SSPS(dt)));
    tsg.SSPS_ADJUSTED_ERROR(dtTsg) = NaN*ones(size(tsg.SSPS(dt)));
    tsg.SSPS_ADJUSTED_QC(dtTsg)    = zeros(size(tsg.SSPS(dt)));

  end

  % Update tsg application data
  % ---------------------------
  setappdata( hMainFig, 'tsg_data', tsg);
  setappdata( hMainFig, 'sample',   sample);

  % everything OK
  % -------------
  error = 1;

else

  % DateMax <= DateMin
  % ------------------
  error = -1;

end


