function [D,xkeep] = getsubsys(D,rowIndex,colIndex,varargin)
% Extracts subsystem.
%
%    Dsub = getsubsys(D,rowIndex,colIndex) extracts the subsystem 
%    sys(rowIndex,colIndex). No structural elimination of states,
%    delays, or blocks is performed. Some uncertain blocks may 
%    be eliminated based on their AutoSimplify settings.
%
%    Dsub = getsubsys(D,rowIndex,colIndex,'smin') eliminates states,
%    delays, and blocks that are structurally decoupled from the 
%    selected inputs or outputs.

%   Author(s): P. Gahinet
%   Copyright 1986-2020 The MathWorks, Inc.
[ny,nu,nz,nw] = getSignalSize(D);
if strcmp(rowIndex,':')
   rowIndex = 1:ny;
else
   rowIndex = reshape(rowIndex,[1 numel(rowIndex)]);
end
if strcmp(colIndex,':')
   colIndex = 1:nu;
else
   colIndex = reshape(colIndex,[1 numel(colIndex)]);
end

% Select I/Os
IC = D.IC;
if isnumeric(IC)
   D.IC = IC([rowIndex,ny+1:ny+nz],[colIndex,nu+1:nu+nw]);
else
   D.IC = getsubsys(D.IC,[rowIndex,ny+1:ny+nz],[colIndex,nu+1:nu+nw]);
end

% Optionally discard disconnected states and delays
if nargin>3
   [D,xkeep] = sminreal(D);
elseif hasState(D)
   xkeep = true(order(D),1);
else
   xkeep = true(order(D.Blocks),1);
end

% Try simplifying uncertain blocks based on their AutoSimplify settings
if any(isUncertain(D.Blocks))
   D = simplify(D,-1,Inf);
end