function [rowIndex,colIndex,rperm,cperm,frows,fcols,ScalarFlag,iRepeat] = ...
   checkRowColIndices(rowIndex,colIndex,lhsSize,rhsSize)
% Checks and format row and column indices for SYS(I,J) = RHS.
% ROWINDEX and COLINDEX are numeric indices or ':'.

%   Copyright 2009-2020 The MathWorks, Inc.

% Turn ':' into a numeric index
if ischar(rowIndex)
   rowIndex = 1:lhsSize(1);
end
if ischar(colIndex)
   colIndex = 1:lhsSize(2);
end

% Check compatibility of ROWINDEX/COLINDEX with size of RHS 
% and detect scalar assignments
nar = numel(rowIndex);  % no. assigned rows
nac = numel(colIndex);  % no. assigned cols
ScalarFlag = (all(rhsSize==1) && (nar~=1 || nac~=1));
if ~ScalarFlag
   if nar~=rhsSize(1)
      % RE: Keep this for cases where RHS is 1xN or Nx1 in which case
      % the IOSIZE assignment in LTI/SUBSASGN may not fail
      error(message('Control:ltiobject:subsasgn5'))
   elseif nac~=rhsSize(2)
      error(message('Control:ltiobject:subsasgn6'))
   end
end
rowIndex = reshape(rowIndex,[1 nar]); % for [frows,rowIndex] below
colIndex = reshape(colIndex,[1 nac]);

% Handle the case where rowIndex or colIndex have repeated indices (g374594)
[~,ir] = unique(rowIndex,'last');
[~,ic] = unique(colIndex,'last');
if length(ir)<nar || length(ic)<nac
   % Reduce to equivalent assignment with nonrepeated indices
   rowIndex = rowIndex(ir);    
   colIndex = colIndex(ic);
   iRepeat = {ir,ic};
else
   iRepeat = {};
end

% Find row and column indices not affected by assignment, and
% compute I/O permutation for which the assignment looks like
%    [sys11  sys12 ;         [sys11  sys12;
%     sys21  sys22 ]   -->    sys21   rhs ]
frows = 1:lhsSize(1);  frows(rowIndex) = [];  % fixed rows
fcols = 1:lhsSize(2);  fcols(colIndex) = [];  % fixed rows
rperm = [frows , rowIndex];           % row permutation
cperm = [fcols , colIndex];           % column permutation