function D = cplx2real(D)
% Turns a complex-valued model into a real-valued model with twice as
% many states, inputs, and outputs.

%   Copyright 1986-2020 The MathWorks, Inc.
a = D.a;
b = D.b;
c = D.c;
d = D.d;
e = D.e;
Delay = D.Delay;
[nyz,nuw] = size(d);

% Double up x,u,y
D.a = [real(a) -imag(a);imag(a) real(a)];
b = [real(b) -imag(b);imag(b) real(b)];
c = [real(c) -imag(c);imag(c) real(c)];
d = [real(d) -imag(d);imag(d) real(d)];
if ~isempty(e)
   D.e = [real(e) -imag(e);imag(e) real(e)];
end
D.dx0 = [real(D.dx0) ; imag(D.dx0)];
D.x0 = [real(D.x0) ; imag(D.x0)];
u0 = [real(D.u0) ; imag(D.u0)];
y0 = [real(D.y0) ; imag(D.y0)];

% Handle internal delays
nfd = numel(Delay.Internal);
if nfd>0
   ny = nyz-nfd;
   nu = nuw-nfd;
   yperm = [1:ny nyz+1:nyz+ny ny+1:nyz nyz+ny+1:2*nyz];
   uperm = [1:nu nuw+1:nuw+nu nu+1:nuw nuw+nu+1:2*nuw];
   D.b = b(:,uperm);
   D.u0 = u0(uperm,:);
   D.c = c(yperm,:);
   D.y0 = y0(yperm,:);
   D.d = d(yperm,uperm);
   Delay.Internal = [Delay.Internal ; Delay.Internal];
else
   D.b = b;
   D.c = c;
   D.d = d;
   D.u0 = u0;
   D.y0 = y0;
end

% Update I/O delays
Delay.Input = [Delay.Input ; Delay.Input];
Delay.Output = [Delay.Output ; Delay.Output];
D.Delay = Delay;
