function G = gabor( wsize, posx, posy, dir, freq, phase, trans, length )
% gabor - constructs 2D gabor-filters...
%
% Reasonable values for inputs:
% wsize = any size
% posx  = -0.5 (left edge) -> 0 (middle) -> 0.5 (right edge)
% posy  = -0.5 (top edge) -> 0 (middle) -> 0.5 (bottom edge)
% dir   = -pi < dir <= pi
% freq  = 0 (0 cycles/pixel) -> wsize*pi (half a cycle per pixel)
% phase = -pi < phase <= pi 
% trans = -pixels <-> +pixels (perpendicular translation, default=0)
%

% Set default values if left out
if nargin==5
  phase = 0;
  trans = 0;
  length = 2;
end

if nargin==6
  trans = 0;
  length = 2;
end

if nargin==7
  length = 2;
end

% normalize to window size=1
trans = trans/wsize;

x=ones(wsize,1)*(1:wsize);
y=x';

% Normalized coordinates
xn = x/wsize - 0.5 - posx;
yn = y/wsize - 0.5 - posy;

% Convert to polar coordinates
r = sqrt(xn.^2 + yn.^2);
d = atan2(yn,xn)-dir;

% De-rotated coordinates
xr = r.*sin(d);
yr = r.*cos(d);

% Edge translation...
xr = xr+trans;

% The choice of the constant 3 in the expression for 'a' is
% quite heuristic and does not come from anywhere in particular.
% It results in gabors that have 2-3 main subregions, which is in
% general agreement with V1 simple cell receptive fields 
% [DeAngelis et al. J. Neurophys. 69: 1091-1117. (1993)]
a = 3/freq;
b = length*a;    

% This generates the gabor
G = cos(xr*freq + phase).*exp(-(xr/a).^2-(yr/b).^2);

return
