function Didtf = idtf(Dtf, varargin)
% Conversion to idtf.

%   Copyright 2009-2013 The MathWorks, Inc.
if nargin>1 && strncmpi(varargin{1},'s',1)
   % Ignore last ny input channels.
   [ny, nu] = iosize(Dtf);
   Dtf = getsubsys(Dtf,':',1:nu-ny);
end  

[num, den, negDelay] = localGetNumDen(Dtf.num, Dtf.den, Dtf.Ts~=0);
ioDelay = Dtf.Delay.IO+negDelay;

% Absorb output delays into IO delay matrix.
ioDelay = ioDelay+repmat(Dtf.Delay.Output,[1 size(ioDelay,2)]);
InputDelay = Dtf.Delay.Input;

if any(ioDelay(:)<0)
   ctrlMsgUtils.warning('Ident:transformation:improperDiscreteLTI','idtf')
   md = min(ioDelay(:));
   InputDelay = InputDelay + md;
   ioDelay = ioDelay - md;
end

TFStruct = pmodel.tf.createMIMO(num,den,ioDelay);
Didtf = idpack.tfdata(TFStruct,Dtf.Ts);
Didtf.Delay.Input = InputDelay;

% Remove superfluous zeros in numerator and denominator since they most
% likley arose from reconciling Nr and Dr lengths.
Didtf = utRemoveZeroPad(Didtf);

% Fix leading zeros in discrete-time case, attributing them to delays and
% lack of feedthrough.
Didtf = fixLeadingZeros(Didtf); % (checks sample time)

%--------------------------------------------------------------------------
function [num, den, negDelay] = localGetNumDen(num, den, isDT)
% Fetch num/den arrays while also normalizing den.
% Return zero access over pole as negative delay for discrete-time data.

if ~iscell(num)
   num = {num};
   den = {den};
end

[ny,nu] = size(num);
negDelay = zeros(ny,nu);

for ct = 1:ny*nu
   numct = num{ct};
   denct = den{ct};
   nr = find(numct,1,'first');
   dr = find(denct,1,'first');
   
   if isempty(nr), nr = min(length(numct),dr); end
   if isDT
      % Remove leading zeros and normalize
      numct = numct(min(nr,dr):end)/denct(dr);
      den{ct} = denct(dr:end)/denct(dr);
      negDelay(ct) = min(nr-dr,0);
      % remove trailing zeros from numerator
      nr2 = find(numct,1,'last');
      if ~isempty(nr2)
         numct = numct(1:nr2);
      end
   else
      % remove leading zeros from numerator
      % (assume them to be fillers)
      nr2 = find(numct,1,'first');
      if ~isempty(nr2)
         numct = numct(nr2:end);
      end
      
      % normalize
      numct = numct/denct(dr);
      den{ct} = denct(dr:end)/denct(dr);
   end   
   num{ct} = numct;
end
