function varargout = hasDelayDynamics(D,PZFLAG)
% Checks if poles depend on internal delays.
%
%   [DP,DY] = hasDelayDynamics(D,'pole') checks if the poles depend on 
%   nonzero internal delays (DP=true). When DP=false, the model equations  
%   are of the form
%      M q'' + C q' + K q = sum_j Bj u(t-tj)
%   When DY=false, the output equation is of the form
%       y = F q + G q' + sum_j Dj u(t-tj) .
%   For static models, DP=DY=false when the output equation is of the form
%       y = sum_j Dj u(t-tj) .
%   
%   DZ = hasDelayDynamics(D,'zero') checks if the transmission zeros depend 
%   on nonzero internal delays (DZ=true). When DZ=false, the internal delays 
%   are equivalent to input and output delays.
%
%   DPZ = hasDelayDynamics(D) returns true when either the poles or zeros
%   depend on nonzero internal delays.

%   Copyright 1986-2023 The MathWorks, Inc.
if nargin<2
   varargout{1} = localDP(D) || localDZ(D);
elseif strcmp(PZFLAG,'pole')
   [varargout{1:nargout}] = localDP(D);
else
   varargout{1} = localDZ(D);
end

%------------------------------------
function [DP,DY] = localDP(D)
% Checks if poles depend on nonzero internal delays
xDelay = D.Delay.Internal;
i2 = find(xDelay>0);
if isempty(i2)
   DP = false;  DY = false;
else
   [ny,nu] = iosize(D);
   d22 = D.d(ny+i2,nu+i2);
   if ltipack.util.isNilpotent(d22~=0)
      % Independence requires D22 nilpotent
      nq = size(D.k,1);
      i1 = find(xDelay==0);
      b2 = [D.b(:,nu+i2);D.d(ny+i1,nu+i2)];
      f2 = [D.f(ny+i2,:),D.d(ny+i2,nu+i1)];
      g2 = [D.g(ny+i2,:),zeros(numel(i2),numel(i1))];
      fg2 = [f2 g2];
      DP = nq>0 && ~isempty(smreal(d22,fg2,b2,[]));
      if nargout>1
         d12 = D.d([1:ny,ny+i1'],nu+i2);
         DY = nq>0 && ~isempty(smreal(d22,fg2,d12,[]));
      end
   else
      DP = true;  DY = true;
   end
end

%------------------------------------
function DZ = localDZ(D)
% Checks if zeros depend on internal delays
% REVISIT
DZ = true;