function [f, gall, NPOINT, NEWLAMBDA, OLDLAMBDA, LOLD, s] = semifun( x, LAMBDA, NEWLAMBDA, OLDLAMBDA, POINT, fun, ntheta, flag, s, P1,P2,P3,P4,P5,P6,P7,P8,P9,P10)
%SEMIFUN Translation routine for semi-infinite optimization.
%	Function used by SEMINF to make semi-infinite problems
%	look like regular constrained optimization problems.

g=[]; f=[]; % Tell parser that f and g are variables.
eval(fun)


gcnt = length(g)+1; 
gncnt = gcnt; 
NPOINT = POINT; 
if length(POINT) == 0
	POINT = zeros(ntheta, 1);
	LAMBDA = zeros(gcnt-1, 1);
	NEWLAMBDA = zeros(gcnt-1, 1);
end
	
delta = []; 
gall = g(:); 
chg = 0; 
if flag  > 0
	NEWLAMBDA = LAMBDA;
end

for i= 1:ntheta
        [gt,d]=eval(['findmax(t',int2str(i),',flag<0)']);
% Find all the maximum points of the data
        nmax=length(gt);
% If the number of maxima is different from las time then change
% LAMBDA and OLDLAMBDA.
% Since the number of maxima is changing then we must try to
% allocate elements of LAMBDA to each of the main peaks.
        nl=POINT(i);
% If the number of maxima is different during  a gradient calculation
% then assign first 'nl' gradients to gt
	if flag > 0
		NPOINT(i,1) = nmax; 
	end
	if flag < 0
		if s~=NaN , s(i,:) = s(i,:).*d;    end
	end
        if nmax~=nl & flag > 0
		chg = 1; 
                [dum,ind]=sort(-gt);
                indl=find(LAMBDA(gcnt:gcnt+nl-1)>0);
                if length(indl)>nmax, indl=indl(1:nmax); end
                sortl=zeros(nmax,1);
                sortl(sort(ind(1:length(indl))))=LAMBDA(gcnt-1+indl);
                NEWLAMBDA=[NEWLAMBDA(1:gncnt-1 );sortl;LAMBDA(gcnt+nl:length(LAMBDA))]; 
		LOLD=NEWLAMBDA;
        end
        gncnt=min(length(NEWLAMBDA)+1, gncnt+nmax);
        gcnt=gcnt+nl;
        delta=[delta;d];
        gall=[gall;gt];
end
if  chg | (flag> 0 & length(OLDLAMBDA) ~= length(gall))
		OLDLAMBDA = NEWLAMBDA + max(OLDLAMBDA);
end

