function f = gauss2Dfit_plane(p,mat)
%--------------------------------------------------------------------------
% 2D gaussian with elliptical profile, free angle and tilted base
% to imgage 'mat'
% the following options are available:
% 
% 'simple'  = no ellipse, no angle, no tilted plane
% 'plane'   = no ellipse, no angle
% 'ellipse' = no tilted plane
% 
% 20080625 TOB (modified from GAUSSIANEVENSLOWER.M by Laurent Holtzer)
%--------------------------------------------------------------------------

p(1);     % x0
p(2);     % y0
p(3);     % A
p(4);     % w
p(5);     % z0
p(6);     % ell
p(7);     % ang
p(8) = 0;     % m
p(9) = 0;     % n

[maxX, maxY] = size(mat);

p(7) = ((2*pi)/360)*p(7); % change degree to radians

efac = 4*log(2)/p(4)^2;
pfac = p(3)*efac/pi;

xv = ones(maxY,1)*[1-p(1):maxX-p(1)];
yv = [1-p(2):maxY-p(2)]'*ones(1,maxX);
x  = -efac*((cos(p(7))*xv+yv*sin(p(7)))/p(6)).^2;
y  = -efac*((cos(p(7))*yv-xv*sin(p(7)))*p(6)).^2;
f  = pfac*exp(y+x)+p(5)+(p(8).*xv + p(9).*yv);

return