function h = fsamp2(f1,f2,hd,siz)
%FSAMP2	2-D FIR filter design via frequency sampling.
%	H = FSAMP2(HD) designs a 2-D FIR filter with desired frequency
%	response HD and returns the coefficients in the matrix H.
%	The returned filter H has a frequency response that passes
%	through the desired frequency response HD. If HD 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 = FSAMP2(F1,F2,HD,[M N]) designs a 2-D FIR filter of size
%	M-by-N by matching the filter response at the points (F1,F2,HD).
%	F1 and F2 are in normalized frequency where 1.0 is the Nyquist
%	frequency.  The filter returned fits the desired response as
%	closely as possible in the least squares sense.  For good 
%	results, there must be at least M*N desired frequency points.
%
%	See also FREQSPACE, FTRANS2, FWIND1, FWIND2.

%	Clay M. Thompson 12-18-92
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.12 $  $Date: 1993/09/07 19:12:33 $

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

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

if nargin==1, % Uniform spacing case (fast)
  hd = f1;

  hd = rot90(fftshift(rot90(hd,2)),2); % Inverse fftshift
  h = fftshift(ifft2(hd));

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

else, % Create filter of size SIZ to solve problem at the points (f1,f2,hd)
  % Expand f1 and f2 if they are vectors.
  if min(size(f1))==1 & min(size(f2))==1 & any(size(hd)~=size(f1)),
    [f1,f2] = meshgrid(f1,f2);
  end

  if prod(size(hd))<prod(siz),
    disp(['WARNING: Not enough desired frequency points.' ...
         '  Results may be inaccurate.']);
  end

  % Convert frequency to radians.
  f1 = f1*pi; f2 = f2*pi;
  h = zeros(siz);
  [n1,n2] = meshgrid((0:siz(2)-1)-floor(siz(2)/2),(0:siz(1)-1)-floor(siz(1)/2));
  DFT = exp(-sqrt(-1)*f1(:)*n1(:)').*exp(-sqrt(-1)*f2(:)*n2(:)');
  h(:) = DFT\hd(:);

end  

% Convert to real if possible.
if all(max(abs(imag(h)))<sqrt(eps)), h = real(h); end

h = rot90(h,2); % Rotate for use with filter2
