function [lambda,GS]=goalfun(V,neqcstr,FUNfcns,GRADfcns,WEIGHT,GOAL,x,varargin)
%GOALFUN Utility function to translate goal-attainment problem.
%
%   Intermediate function used to translate goal attainment
%   problem into constrained optimization problem.
%   Used by ATTGOAL and CONSTR. 
%   
%   See also GOALGRA.

%   Copyright (c) 1990-98 by The MathWorks, Inc.
%   $Revision: 1.1 $  $Date: 1998/04/05 21:19:38 $
%   Andy Grace 7-9-90.

% Note: attgoal does not use g; minimax uses g
g=[]; f=[];  % Tell parser that f and g are variables.
nx=length(V)-1;
% Assign V to x, keeping x to be its original length and width
x(:)=V(1:nx);
lambda=V(nx+1);


[f,g,msg]=opteval(x,FUNfcns,varargin{:});
ncstr=length(WEIGHT);

% neqcstr comes from options(15), not options(13), for minimax and attgoal
GS = zeros(ncstr+neqcstr,1);
for i=1:ncstr
     if WEIGHT(i)~=0
       diff=f(i)-GOAL(i);
       GS(i)=sign(real(diff))*norm(diff)/WEIGHT(i)-lambda;
       if i<=neqcstr, GS(i+ncstr)=-GS(i)-2*lambda; end
      else
       GS(i)=f(i)-GOAL(i);
       if i<=neqcstr, GS(i+ncstr)=-GS(i)-1e-10; end
     end
end
% Put g constraints first to allow equality constraints in minimax
%  (note: attgoal problems have no "g" argument.)
GS=[g(:);GS]; 

