function [D,xkeep] = sminrealXC(D)
% Structurally minimal realization with state and delay consistency.
% Eliminates the same states and delays across all models in SS array.

%   Author(s): P. Gahinet
%   Copyright 2022-2023 The MathWorks, Inc.

% Build collective (A,B,C,D) structure
nx = size(D(1).a,1);
[nyz,nuw] = size(D(1).d);
nfd = numel(D(1).Delay.Internal);
ny = nyz-nfd;
nu = nuw-nfd;
outer = sparse(ones(1,nu),1:nu,ones(1,nu),1,nuw); % [ones(1,nu),zeros(1,nfd)]
a = sparse(nx,nx);
b = sparse(nx,nuw);
c = sparse(nyz,nx);
d = sparse(nyz,nuw);
e = [];
try
   for ct=1:numel(D)
      a = a + spones(D(ct).a);
      b = b + spones(D(ct).b) + spones(D(ct).dx0) * outer;
      c = c + spones(D(ct).c);
      d = d + spones(D(ct).d);
      if isempty(e)
         if ~isempty(D(ct).e)
            e = speye(nx) + spones(D(ct).e);
         end
      else
         if isempty(D(ct).e)
            e = e + speye(nx);
         else
            e = e + spones(D(ct).e);
         end
      end
   end
catch
   error(message('Control:transformation:sminreal2'))
end

% Simplify states and delays
if nfd==0
   [~,~,~,~,xkeep] = smreal(a,b,c,e);
   ix = find(xkeep);
   id = [];
else
   if ~isempty(e)
      e = blkdiag(e,speye(nfd));
   end
   [~,~,~,~,xdkeep] = smreal([a b(:,nu+1:nuw);c(ny+1:nyz,:) d(ny+1:nyz,nu+1:nuw)],...
      [b(:,1:nu) ; d(ny+1:nyz,1:nu)], [c(1:ny,:) , d(1:ny,nu+1:nuw)], e);
   xkeep = xdkeep(1:nx,:);
   ix = find(xkeep);
   id = find(xdkeep(nx+1:nx+nfd,:))';
end
for ct=1:numel(D)
   D(ct).a = D(ct).a(ix,ix);
   D(ct).b = D(ct).b(ix,[1:nu nu+id]);
   D(ct).c = D(ct).c([1:ny ny+id],ix);
   if ~isempty(D(ct).e)
      D(ct).e = D(ct).e(ix,ix);
   end
   D(ct).dx0 = D(ct).dx0(ix,:);
   D(ct).x0 = D(ct).x0(ix,:);
   D(ct).Delay.Internal = D(ct).Delay.Internal(id,:);
   if ~isempty(D(ct).StateName)
      D(ct).StateName = D(ct).StateName(ix,:);
   end
   if ~isempty(D(ct).StatePath)
      D(ct).StatePath = D(ct).StatePath(ix,:);
   end
   if ~isempty(D(ct).StateUnit)
      D(ct).StateUnit = D(ct).StateUnit(ix,:);
   end
end
