function updateAdjustedVariable( hMainFig )
%
% Update adjusted SSPS, SSJT, and SSTP arrays with calibrated
% variables if they exist
%
% The TRICK :  
% The programe test the variable ADJUSTED_ERROR as only records corrected
% compared to water sample get error values
%

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

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

% Variables
% ---------
PARA = [ 'SSPS'; 'SSJT'; 'SSTP' ];

for i = 1 :3

  para1 = [ PARA(i,:) '_CAL' ];
  para2 = [ PARA(i,:) '_ADJUSTED' ];
  para3 = [ PARA(i,:) '_ADJUSTED_QC' ];
  para4 = [ PARA(i,:) '_ADJUSTED_ERROR' ];
  para5 =   PARA(i,:);
  para6 = [ PARA(i,:) '_QC' ];
  
  % The variable must exist
  % -----------------------
  if ~isempty( tsg.(para5) )

    % If no correction have been made and CAL parameter exists, the
    % ADJUSTED variable is set to CAL
    % -------------------------------------------------------------
    if isempty( tsg.(para4) ) && ~isempty( tsg.(para1) )
      
      tsg.(para2) = tsg.(para1);
      tsg.(para3) = tsg.(para6);
      
    elseif  isempty( tsg.(para4) ) && isempty( tsg.(para1) )

      % No Correction and no Calibrated records : ADJUSTED variable is
      % empty
      % --------------------------------------------------------------
      tsg.(para2) = [];
      tsg.(para3) = [];
      
    elseif ~isempty( tsg.(para4) )  % If ERROR not empty

      % The QC code are set to the QC code of the raw variable
      % ------------------------------------------------------
      tsg.(para3) = tsg.(para6);

      % Get Adjusted records that were not corrected using Water samples
      % Only records corrected get error values
      % ----------------------------------------------------------------
      ind = find( isnan(tsg.(para4) ) == 1);
      
      % If the parameter has been calibrated
      % ------------------------------------
      if ~isempty( tsg.(para1) )
        
        % Adjusted records not corrected are set to the calibrated value
        % --------------------------------------------------------------
        if ~isempty( ind )
          tsg.(para2)(ind) = tsg.(para1)(ind);
        end
        
      else
        
        % Adjusted records not corrected are set to the raw value
        % -------------------------------------------------------
        if ~isempty( ind )
          tsg.(para2)(ind) = tsg.(para5)(ind);
        end
      end
      
    end
  end

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

end