function vinit = filtic( b, a, ypast, xpast )
%FILTIC	Make initial conditions for filter() function.
%   V = filtic( B, A, Y, X )
%      converts past values of x[n] & y[n] into initial conditions
%       for the state variables v_i[n] needed in the
%       TRANSPOSED DIRECT FORM II filter structure.
%   V = filtic( B, A, Y ) assumes that x[n] = 0 in the past.
%      The vector of past inputs & outputs stored as:
%          xpast = [ x[-1] x[-2] x[-3] ... x[-nb] ]
%          ypast = [ y[-1] y[-2] y[-3] ... y[-na] ]
%    NOTE: if not enough past values are given, then
%          zeropad x[n] or y[n] as needed.
%
if nargin == 3
   xpast = [0];   % this is the zero input condition
end
na = length(a);   nb = length(b);
m = max([na nb]) - 1;
if( m < 1 )
   vinit = [];  return
end
Lx = length(xpast);   Ly = length(ypast);
if( Lx < (nb-1) ),   xpast(nb-1) = 0;    end   %--- zero pad
if( Ly < (na-1) ),   ypast(na-1) = 0;    end
vinit = zeros(1,m);  vx = vinit;
% --- use filter() to do convolution
if( na-1 > 0 )
  vinit((na-1):-1:1) = filter( -a(na:-1:2)/a(1), 1, ypast(1:(na-1)) );
end
if( nb-1 > 0 )
  vx((nb-1):-1:1) = filter( b(nb:-1:2)/a(1), 1, xpast(1:(nb-1)) );
end
vinit = vinit + vx;
