function utCheckTsTimeUnit(inputArgs,dataTypeUsed)
% Check for sampling time and time unit match between data and name-value
% pairs

% Copyright 2023 The MathWorks, Inc.

data = inputArgs{1};
command = inputArgs{end};

TsData = data.Ts;
TimeUnitData = data.TimeUnit;
TsPV = [];
TimeUnitPV = [];

IdxTs = idpack.findOptionInList('Ts',inputArgs,2);
IdxTimeUnit = idpack.findOptionInList('TimeUnit',inputArgs,5);

if ~isempty(IdxTs)
   TsPV = inputArgs{IdxTs + 1};
   if isempty(TsPV)
      error(message('Ident:utility:emptySampleTimeNotSupported'));
   elseif TsPV == 0 && ~any(strcmpi(command,{'tfest','ssest','procest',...
         'n4sid','pem','greyest','nlgreyest','ssregest'}))
      error(message('Ident:estimation:invalidZeroTsValue'));
   end
end

if ~isempty(IdxTimeUnit)
   TimeUnitPV = inputArgs{IdxTimeUnit + 1};
   TimeUnitPV = ltipack.matchKey(TimeUnitPV,ltipack.getValidTimeUnits());
   if isempty(TimeUnitPV)
      TimeUnitPV = TimeUnitData;
   end
end

if ~isempty(TsPV) && ~strcmpi(dataTypeUsed,'numeric')
   if iscell(TsData)
      TsData = TsData{1};
   end
   if TsPV ~= 0 && ~isempty(TsData) && TsPV ~= -1 && abs(TsData - TsPV) > eps
      if strcmpi(command,'procest')
         % idproc models sampling time must be zero
         error(message('Ident:idmodel:idprocInvalidTs'))
      else
         % check that TimeUnits are equal
         error(message('Ident:estimation:dataModelTsMismatch'))
      end
   end
end

if ~isequal(TimeUnitData,TimeUnitPV) && ~isempty(TimeUnitPV)
   error(message('Ident:utility:TimeUnitValuesDoesnotMatch'))
end

end
