function D = diagrep(D,k)
% Replicates model along the diagonal.
%
%   D = DIAGREP(D,K) forms the block-diagonal model Diag(D,...,D) with 
%   D repeated K times.

%   Copyright 2020 The MathWorks, Inc.
I = speye(k);
if ~isempty(D.m)
   D.m = kron(I,D.m);
end
D.c = kron(I,D.c);
D.k = kron(I,D.k);
D.Delay.Input = repmat(D.Delay.Input,[k 1]);
D.Delay.Output = repmat(D.Delay.Output,[k 1]);
nfd = length(D.Delay.Internal);
if nfd==0
   D.b = kron(I,D.b);
   D.f = kron(I,D.f);
   D.g = kron(I,D.g);
   D.d = kron(I,D.d);
else
   [rs,cs] = size(D.d);
   nu = cs-nfd;
   ny = rs-nfd;
   D.b = [kron(I,D.b(:,1:nu)) , kron(I,D.b(:,nu+1:cs))];
   D.f = [kron(I,D.f(1:ny,:)) ; kron(I,D.f(ny+1:rs,:))];
   D.g = [kron(I,D.g(1:ny,:)) ; kron(I,D.g(ny+1:rs,:))];
   D.d = [kron(I,D.d(1:ny,1:nu)) kron(I,D.d(1:ny,nu+1:cs)) ; ...
      kron(I,D.d(ny+1:rs,1:nu)) kron(I,D.d(ny+1:rs,nu+1:cs))];
   D.Delay.Internal = repmat(D.Delay.Internal,[k 1]);
end
D.StateInfo = repmat(D.StateInfo,[k 1]);
