function y = fftfilt(b,x,nfft)
%FFTFILT Overlap-add method of filtering using FFT.
%	Y = FFTFILT(B,X) filters X with the FIR filter B using
%	the overlap/add method.
%	Y = FFTFILT(B,X,N) uses to overlap/add method to filter
%	X with B using an N-point FFT.
%	See also FILTER.

%	Author: L. Shure 7-27-88
%	Revised: LS, 4-25-90
%	(c) Copyright 1987-90, by The MathWorks, Inc.

%	Reference:
%	   A.V. Oppenheim and R.W. Schafer, Digital Signal 
%	      Processing, Prentice-Hall, 1975.


if nargin < 3
	nfft = 512;
end
[m,n] = size(x);
y = zeros(m,n);
nx = max(m,n);
if m > n
	b = b(:);
end
nb = length(b);
if nb > nfft
	nfft = nb;
end
nfft = 2.^(ceil(log(nfft)/log(2))); % force this to a power of 2 for speed
if nx < nfft	% see if we can make this less than 512 or nfft
	powerof2 = 2.^(ceil(log(nx)/log(2)));
	if (powerof2 < nfft) & (nargin < 3) & (nb <= nx)
		nfft = powerof2;
	end
end
B = fft(b,nfft);
L = nfft - nb + 1;
istart = 1;
while istart <= nx
	iend = min(istart+L-1,nx);
	X = fft(x(istart:iend),nfft);
	Y = ifft(X.*B);
	yend = min(nx,istart+nfft-1);
	y(istart:yend) = y(istart:yend) + Y(1:(yend-istart+1));
	istart = istart + L;
end
if ~any(imag(b)) & ~any(imag(x))
	y = real(y);
end

