function [A,B,C,D,E,dx0,x0,u0,y0,Delay] = appendDF(sys1,sys2,t,p1,p2)
% Constructs data function for APPEND concatenation of LTVSS/LPVSS models.

%   Copyright 2022-2023 The MathWorks, Inc.
if nargin<4
   [A1,B1,C1,D1,E1,dx01,x01,u01,y01,Delay1] = sys1.DataFunction(t);
   [A2,B2,C2,D2,E2,dx02,x02,u02,y02,Delay2] = sys2.DataFunction(t);
else
   [A1,B1,C1,D1,E1,dx01,x01,u01,y01,Delay1] = sys1.DataFunction(t,p1);
   [A2,B2,C2,D2,E2,dx02,x02,u02,y02,Delay2] = sys2.DataFunction(t,p2);
end
nx1 = size(A1,1);  nx2 = size(A2,1);
A = ltipack.util.blkdiag(A1,A2);
E = ltipack.util.blkdiagE(E1,E2,nx1,nx2);

% Combine  offsets
if isempty(x01) && isempty(x02)
   x0 = [];
else
   [x01,x02] = ltvpack.util.matchOffset(x01,nx1,x02,nx2);
   x0 = [x01;x02];
end
if isempty(dx01) && isempty(dx02)
   dx0 = [];
else
   [dx01,dx02] = ltvpack.util.matchOffset(dx01,nx1,dx02,nx2);
   dx0 = [dx01;dx02];
end

if isempty(Delay1) && isempty(Delay2)
   % Delay-free case
   [ny1,nu1] = size(D1);
   [ny2,nu2] = size(D2);
   B = ltipack.util.blkdiag(B1,B2);
   C = ltipack.util.blkdiag(C1,C2);
   D = ltipack.util.blkdiag(D1,D2);
   Delay = [];
   if isempty(u01) && isempty(u02)
      u0 = [];
   else
      [u01,u02] = ltvpack.util.matchOffset(u01,nu1,u02,nu2);
      u0 = [u01;u02];
   end
   if isempty(y01) && isempty(y02)
      y0 = [];
   else
      [y01,y02] = ltvpack.util.matchOffset(y01,ny1,y02,ny2);
      y0 = [y01;y02];
   end
else
   % Note: All input and output delays not explicitly marked as absent ([])
   % are assumed varying and turned into internal delays.
   [nyz1,nuw1] = size(D1);
   [nyz2,nuw2] = size(D2);
   [Delay1,Delay2] = ltvpack.util.matchDelay(Delay1,[nyz1,nuw1],Delay2,[nyz2,nuw2]);
   Delay = struct('Input',[Delay1.Input;Delay2.Input],...
      'Output',[Delay1.Output;Delay2.Output],...
      'Internal',[Delay1.Internal;Delay2.Internal]);
   nfd1 = numel(Delay1.Internal);
   ny1 = nyz1-nfd1;   nu1 = nuw1-nfd1;
   nfd2 = numel(Delay2.Internal);
   ny2 = nyz2-nfd2;   nu2 = nuw2-nfd2;
   B = [ltipack.util.blkdiag(B1(:,1:nu1),B2(:,1:nu2)) ,...
      ltipack.util.blkdiag(B1(:,nu1+1:nuw1),B2(:,nu2+1:nuw2))];
   C = [ltipack.util.blkdiag(C1(1:ny1,:),C2(1:ny2,:)) ;...
      ltipack.util.blkdiag(C1(ny1+1:nyz1,:),C2(ny2+1:nyz2,:))];
   D = [ltipack.util.blkdiag(D1(1:ny1,1:nu1),D2(1:ny2,1:nu2)) , ...
      ltipack.util.blkdiag(D1(1:ny1,nu1+1:nuw1),D2(1:ny2,nu2+1:nuw2)) ; ...
      ltipack.util.blkdiag(D1(ny1+1:nyz1,1:nu1),D2(ny2+1:nyz2,1:nu2)) , ...
      ltipack.util.blkdiag(D1(ny1+1:nyz1,nu1+1:nuw1),D2(ny2+1:nyz2,nu2+1:nuw2))];
   if isempty(u01) && isempty(u02)
      u0 = [];
   else
      [u01,u02] = ltvpack.util.matchOffset(u01,nuw1,u02,nuw2);
      u0 = [u01(1:nu1,:);u02(1:nu2,:);u01(nu1+1:nuw1,:);u02(nu2+1:nuw2,:)];
   end
   if isempty(y01) && isempty(y02)
      y0 = [];
   else
      [y01,y02] = ltvpack.util.matchOffset(y01,nyz1,y02,nyz2);
      y0 = [y01(1:ny1,:);y02(1:ny2,:);y01(ny1+1:nyz1,:);y02(ny2+1:nyz2,:)];
   end
end
