function h = fwind2(f1,f2,hd,w)
%FWIND2	2-D FIR filter design using 2-D window.
%	H = FWIND2(HD,W) designs a 2-D FIR filter with frequency
%	response HD and returns the coefficients in the matrix H.
%	H is computed by applying the 2-D window W to the inverse
%	Fourier transform of the desired response.  The size of W
%	controls of the size of the resulting filter: if W is M-by-N
%	then H will be M-by-N.  HD is a complex matrix containing
%	the desired frequency response sampled at equally spaced
%	points between -1 to 1 (the Nyquist frequency) along the x
%	and y frequency axes (see FREQSPACE for more info).
%
%	H = FWIND2(F1,F2,Hd,W) designs a 2-D FIR filter using the
%	desired frequency response defined at the points (F1,F2,HD).
%	F1 and F2 are in normalized frequency where +/-1.0 corresponds
%	to the Nyquist frequency.  The filter returned will be the same
%	size as W.
%
%	See also FREQSPACE, FSAMP2, FTRANS2, and FWIND1.

%	Clay M. Thompson 1-15-92
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.14 $  $Date: 1993/09/09 23:01:15 $

% Reference: "Two Dimensional Signal and Image Processing" by Jae S. Lim,
%            pages 213-217.

error(nargchk(2,4,nargin));

method = 'bilinear';

if nargin==2, % Uniform spacing case
  hd = f1; w = f2;
  if any(size(w)~=size(hd)), % Interpolate Hd to be the same size as W
    if any(size(hd)<[2 2]),
      error('Hd must have at least 2 rows and 2 columns.');
    end
    [f1,f2] = freqspace(size(hd));
    % Extrapolate hd so that interpolation is never out of range.
    [mh,nh] = size(hd);
    if floor(nh/2)==nh/2, % if even
      hd = [hd,hd(:,1)]; f1 = [f1 1];
    else
      hd = [zeros(mh,1) hd zeros(mh,1)]; 
      df = f1(2)-f1(1); f1 = [f1(1)-df f1 f1(nh)+df];
    end
    [mh,nh] = size(hd);
    if floor(mh/2)==mh/2, % if even
      hd = [hd;hd(1,:)]; f2 = [f2 1];
    else
      hd = [zeros(1,nh);hd;zeros(1,nh)]; 
      df = f2(2)-f2(1); f2 = [f2(1)-df f2 f2(mh)+df];
    end
    [i1,i2] = freqspace(size(w),'meshgrid');
    hd = interp2(f1,f2,hd,i1,i2,method);
    d = find(isnan(hd)); if ~isempty(d), hd(d) = zeros(size(d)); end
  end
  h = fsamp2(hd) .* w;

elseif nargin==3,
  error('Wrong number of input arguments.');

else % Non-uniform spacing case
  h = fsamp2(f1,f2,hd,size(w)) .* w;

end
