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 1990-2000 The MathWorks, Inc.
%   $Revision: 1.2 $  $Date: 2000/06/16 22:24:34 $
%   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]; 

