function [c_all,ceq,NPOINT,NEWLAMBDA,OLDLAMBDA,LOLD,s] = semifun(x,LAMBDA,NEWLAMBDA,OLDLAMBDA,POINT,flag,s,ntheta,FunName,varargin)
%SEMIFUN Translation routine for semi-infinite optimization.
%       Function used by SEMINF to make semi-infinite problems
%       look like regular constrained optimization problems.

%   Copyright (c) 1990-98 by The MathWorks, Inc.
%   $Revision: 1.1 $  $Date: 1998/04/07 22:07:14 $

c=[]; ceq=[];% Tell parser that ceq and c are variables.
% Call user-function: [c,ceq,t1,...,tntheta,s]=fun(x,s,varargin{:});
% eval(FunName)
eval(FunName);


LOLD = [];
ccnt = length(c)+1; 
cncnt = ccnt; 
NPOINT = POINT; 
if length(POINT) == 0
    POINT = zeros(ntheta, 1);
    LAMBDA = zeros(ccnt-1, 1);
    NEWLAMBDA = zeros(ccnt-1, 1);
end
    
delta = []; 
%% V5 update:

if isempty(c), c_all=[]; else, c_all=c(:); end

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 last 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 ~isnan(s) , s(i,:) = s(i,:).*d;    end
    end
        if nmax~=nl & flag > 0
        chg = 1; 
                [dum,ind]=sort(-gt);
                indl=find(LAMBDA(ccnt:ccnt+nl-1)>0);
                if length(indl)>nmax, indl=indl(1:nmax); end
                sortl=zeros(nmax,1);
                sortl(sort(ind( (1:length(indl))' )))=LAMBDA(ccnt-1+indl);
                NEWLAMBDA=[NEWLAMBDA( (1:cncnt-1)' ); ...
                  sortl; LAMBDA( (ccnt+nl:length(LAMBDA))' )]; 
        LOLD=NEWLAMBDA;
        end
        cncnt=min(length(NEWLAMBDA)+1, cncnt+nmax);
        ccnt=ccnt+nl;
        delta=[delta;d];
        c_all=[c_all;gt];
end
if  chg | (flag> 0 & length(OLDLAMBDA) ~= length(c_all))
        %% V5 update:
        if ~isempty(OLDLAMBDA)
          OLDLAMBDA = NEWLAMBDA + max(OLDLAMBDA);
        end
end
