function [D1,ElimFlag] = mtimes(D1,D2,ScalarFlags)
% Multiplies two transfer functions D = D1 * D2.

%   Copyright 1986-2012 The MathWorks, Inc.
if nargin<3
   ScalarFlags = false(1,2);
end

% Delay management along inner dimension. On output, D1 contains
% the overall delays for the series connection.
[D1,D2,ElimFlag] = mtimesDelay(D1,D2,ScalarFlags);

% Perform multiplication
if ScalarFlags(1)
   % Scalar multiplication sys1 * SYS2 with sys1 SISO
   scalnum = D1.num{1};
   scalden = D1.den{1};
   [ny,nu] = size(D2.num);
   num = cell(ny,nu);
   den = cell(ny,nu);
   for ct=1:ny*nu
      nct = conv(scalnum,D2.num{ct});
      if ~any(nct)
         num{ct} = 0;  den{ct} = 1;
      else
         num{ct} = nct;
         den{ct} = conv(scalden,D2.den{ct});
      end
   end 
elseif ScalarFlags(2)
   % Scalar multiplication SYS1 * sys2 with sys2 SISO
   scalnum = D2.num{1};
   scalden = D2.den{1};
   [ny,nu] = size(D1.num);
   num = cell(ny,nu);
   den = cell(ny,nu);
   for ct=1:ny*nu
      nct = conv(scalnum,D1.num{ct});
      if ~any(nct)
         num{ct} = 0;  den{ct} = 1;
      else
         num{ct} = nct;
         den{ct} = conv(scalden,D1.den{ct});
      end
   end
else
   % Regular multiplication
   ny = size(D1.num,1);
   [nin,nu] = size(D2.num);
   num = cell(ny,nu);
   den = cell(ny,nu);
   if nin==1
      % Unit inner dimension (SISO products)
      for j=1:nu
         for i=1:ny
            [num{i,j},den{i,j}] = utAddSISO(0,1,...
               conv(D1.num{i},D2.num{j}),...
               conv(D1.den{i},D2.den{j}));
         end
      end
   else
      % MIMO case
      for j=1:nu
         for i=1:ny
            nij = 0;
            dij = 1;
            % Evaluate sum of D1(i,k)*D2(k,j) for k=1:m1
            for m=1:nin,
               [nij,dij] = utAddSISO(nij,dij,...
                  conv(D1.num{i,m},D2.num{m,j}),...
                  conv(D1.den{i,m},D2.den{m,j}));
            end
            num{i,j} = nij;
            den{i,j} = dij;
         end
      end
   end
end

% Check for NaNs (could arise in sys1/sys2)
NaNFlag = cellfun(@(x) any(isnan(x)),num);
if any(NaNFlag(:))
   num(:) = {NaN};   den(:) = {1};
   D1.num = num;  D1.den = den;
else
   % Remove leading zeros in both NUM,DEN (assumption that NUM(1) or DEN(1) 
   % is nonzero is pervasive in @tfdata code)
   [D1.num,D1.den] = ltipack.tfdata.utTrimNumDen(num,den,false);
end
