function [A,B,G,Q,R,S,E,AutoScaling,JOB] = parseInputs(DOMAIN,A,B,Q,varargin)
% Checks input arguments to ICARE and IDARE.

%   Copyright 1986-2021 The MathWorks, Inc.

% Look for flags
AutoScaling = true;  JOB = 's';  % defaults
iFlag = find(cellfun(@(x) ischar(x) || isstring(x),varargin));
for ct=1:numel(iFlag)
   switch varargin{iFlag(ct)}
      case 'noscaling'
         AutoScaling = false;
      case 'anti'
         JOB = 'a';
      otherwise
         error(message('Control:foundation:ARE01'))
   end
end
varargin(iFlag) = [];
ni = numel(varargin);

% A matrix
A = double(A);
n = size(A,1);
if ~allfinite(A)
   error(message('Control:foundation:NoInfNaN','A'))
elseif size(A,2)~=n
   error(message('Control:foundation:ARE02'))
end

% B matrix
B = double(B);
m = size(B,2);
if isempty(B)
   B = zeros(n,m);
elseif ~allfinite(B)
   error(message('Control:foundation:NoInfNaN','B'))
elseif size(B,1)~=n
   error(message('Control:foundation:ARE08'))
end

% Q,R,S matrices
R = [];  S = [];
if ni>0
   R = varargin{1};
end
if ni>1
   S = varargin{2};
end
[Q,R,S] = ltipack.checkQRS(n,m,Q,R,S,{'Q','R','S'});

% E matrix
if ni<3
   E = [];  % ltipack.iCARE uses explicit form when E=[] and m=0
else
   E = double(varargin{3});
   if ~allfinite(E)
      error(message('Control:foundation:NoInfNaN','E'))
   elseif ~(isempty(E) || isequal(size(E),[n n]))
      error(message('Control:foundation:ARE06'))
   end
end

% G matrix (continuous-time only)
if DOMAIN=='c'
   if ni>3
      G0 = double(varargin{4});
   else
      G0 = [];
   end
   if isempty(G0)
      G = zeros(n);
   elseif ~allfinite(G0)
      error(message('Control:foundation:NoInfNaN','G'))
   else
      if isscalar(G0)
         G = real(G0) * eye(n);
      elseif ~isequal(size(G0),[n n])
         error(message('Control:foundation:ARE09'))
      else
         G = (G0+G0')/2;
      end
      if norm(G0-G0',1) > 1e3*eps*norm(G0,1)
         warning(message('Control:foundation:ARE07','G'))
      end
   end
else
   if ni>3 && ~isempty(varargin{4})
      error(message('Control:foundation:ARE01'))
   end
   G = [];
end
