function [D,SingularFlag] = connect(D,K,feedin,feedout,extin,extout,Options)
% Closes the loop U(FEEDIN) = K*Y(FEEDOUT) and selects
% channel EXTIN and EXTOUT as external I/Os. The
% structurally nonminimal dynamics wrt the selected
% external I/Os are discarded.

%   Copyright 2020 The MathWorks, Inc.

% Close feedback loops
if isempty(K)
   SingularFlag = false;
else
   [D,SingularFlag] = feedback(D,createGain(D,K),feedin,feedout,+1);
end

% Select external I/Os and optionally discard dynamics that are disconnected
% from these inputs or outputs
if isempty(Options) || Options.Simplify
   D = getsubsys(D,extout,extin,'smin');
else
   D = getsubsys(D,extout,extin);
end