function [Q,R,S] = checkQRS(n,m,Q0,R0,S0,MatNames)
% Validates Q,R,S matrices for Riccati solvers and LQR/LQG design.

%   Copyright 2018-2021 The MathWorks, Inc.

% Q matrix
Q0 = double(Q0);
if isempty(Q0)
   Q = zeros(n);
elseif ~allfinite(Q0)
   error(message('Control:foundation:NoInfNaN',MatNames{1}))
else
   if isscalar(Q0)
      Q = real(Q0) * eye(n);
   elseif ~isequal(size(Q0),[n n])
      error(message('Control:foundation:WrongSize1',MatNames{1},n))
   else
      Q = (Q0+Q0')/2;
   end
   if norm(Q0-Q0',1) > 1e3*eps*norm(Q0,1)
      warning(message('Control:foundation:ARE07',MatNames{1}))
   end
end

% R matrix
R0 = double(R0);
if isempty(R0)
   R = eye(m);
elseif ~allfinite(R0)
   error(message('Control:foundation:NoInfNaN',MatNames{2}))
else
   if isscalar(R0)
      R = real(R0) * eye(m);
   elseif ~isequal(size(R0),[m m])
      error(message('Control:foundation:WrongSize1',MatNames{2},m))
   else
      R = (R0+R0')/2;
   end
   if norm(R0-R0',1) > 1e3*eps*norm(R0,1)
      warning(message('Control:foundation:ARE07',MatNames{2}))
   end
end

% S matrix
S = double(S0);
if isempty(S) || isequal(S,0)
   S = zeros(n,m);
elseif ~allfinite(S)
   error(message('Control:foundation:NoInfNaN',MatNames{3}))
elseif ~isequal(size(S),[n m])
   error(message('Control:foundation:WrongSize2',MatNames{3},n,m))
end
