function [hout,w1,w2] = freqz2(a,n1,n2,dx)
%FREQZ2	Two dimensional frequency response.
%	[H,w1,w2] = FREQZ2(A,N1,N2) returns the N2-by-N1 frequency
%	response of the 2-D FIR filter A and the frequency vectors w1 
%	(of length N1) and w2 (of length N2). [...] = FREQZ2(A,[N2 N1])
%	also works.
%	                jw1  jw2                            -n1  -n2
%	  H(w1,w2) = A(e   ,e   ) = sum_n1 sum_n2 a(n1,n2)z1   z2
%
%	[H,w1,w2] = FREQZ2(A,w1,w2) returns the frequency response
%	for the frequency points in w1,w2. w1 and w2 must contain
%	values in the range -1.0 to 1.0 (the Nyquist frequencies).
%
%	[H,w1,w2] = FREQZ2(A) uses the default 64-by-64 response.
%	
%	The intersample spacing [DX DY] in A can be used to set the 
%	frequency axis by using [...] = FREQZ2(A,N1,N2,[DX DY]) or 
%	[...] = FREQZ2(A,w1,w2,[DX DY]).  The default intersample 
%	spacing is 0.5 in both directions.
%
%	Without output arguments, FREQZ2(...) produces a mesh plot of 
%	the 2-D frequency response magnitude.
%
%	See also FREQZ for 1-D signals.

%	Clay M. Thompson 1-7-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.13 $  $Date: 1993/09/09 14:31:19 $

if nargin<2, n1 = 64; n2 = 64; end 	% Default number of frequency points
if nargin==2, 
  if all(size(n1)==[1 2]), 
    n2 = n1(1); n1 = n1(2);
  elseif max(size(n1)==1)
    n2 = n1;
  else
    error('Not enough input arguments.');
  end
end
if nargin<4, dx = [0.5 0.5]; end % Default intersample spacing
if max(size(dx))==1, dx = [dx dx]; end % Allow scalar dx

% Check for n1 and n2 < size(a).  If so, switch to w1,w2 based calc.
if (max(size(n1))==1) & (max(size(n2))==1), % N equally spaced points
  if any(size(a)>[n2 n1]),
    n1 =  ((0:n1-1)-floor(n1/2))*(1/(n1*dx(1)));
    n2 = (((0:n2-1)-floor(n2/2))*(1/(n2*dx(2))))';
  end
end

a = rot90(a,-2); % Unrotate filter since FIR filters are rotated.
if (max(size(n1))==1) & (max(size(n2))==1), % N equally spaced points
  % Pad A if necessary
  if any(size(a)~=[n2 n1]),
    [ma,na] = size(a);
    aa = zeros(n2,n1);
    aa(floor(n2/2)-floor(ma/2)+(1:ma),floor(n1/2)-floor(na/2)+(1:na)) = a;
    a = aa;
  end
  a = rot90(fftshift(rot90(a,2)),2); % Inverse fftshift
  w1 =  ((0:n1-1)-floor(n1/2))*(1/(n1*dx(1)));
  w2 = (((0:n2-1)-floor(n2/2))*(1/(n2*dx(2))))';
  h = fftshift(fft2(a));

else % evaluate frequency response at points in n1.
  % Expand w1 and w2 if they are vectors
  if min(size(n1))==1 | min(size(n2))==1, 
    [w1,w2] = meshgrid(n1,n2);
  else
    w1 = n1; w2 = n2;
  end
  [t1,t2] = freqspace(size(a)); 
  t1 = t1*size(a,2)/2; 
  t2 = t2*size(a,1)/2;
  [t1,t2] = meshgrid(t1,t2);
  h = zeros(size(w1));
  h(:) = (exp(-sqrt(-1)*pi*w1(:)*t1(:)').*exp(-sqrt(-1)*pi*w2(:)*t2(:)'))*a(:);
end

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

if nargout==0, % Plot data
  mesh(w1,w2,abs(h))
  xlabel('Frequency'), ylabel('Frequency'), zlabel('Magnitude')
  return
end
hout = h;
w1 = w1(1,:)';
w2 = w2(:,1);
