function [potential, gradient] = grad_V(x, y, parms);
% Compute potential and gradient vector for 2D model potential.
%
% ARGUMENTS
%  x, y - x and y coordinates
%  params - parameters specifying the potential

% Extract potential parameters.
x0=parms(:,1);  y0=parms(:,2);
R1=parms(:,3);  R2=parms(:,4);
theta=parms(:,5); gamma=parms(:,6); w=parms(:,7); 

% Initialize calculation of probability and gradient vectors.
Q=0;dq=0; dz=0; GV = zeros(2,1);

% Compute contributions from each Gaussian component.
for i=1:length(R1)
   R=[cos(theta(i)) sin(theta(i)); -sin(theta(i)) cos(theta(i))];
   S=[R1(i)^2 0 ; 0 R2(i)^2];
   G=R'*S^-1*R;
   G_h=0.5*gamma(i)*G;
   q=[x-x0(i);y-y0(i)];
   s_i=G_h*q;
   g_i=w(i)*exp(-q'*G_h*q);
   GV=GV+g_i*s_i;
   dz=dz + g_i;
%   keyboard;
end

% Compute gradient and potential
gradient = 2*GV/dz;
potential = - log(dz);

return
