%================================================
% Differential Migration for Time Delay Toolbox
%================================================

echo off;
warning off;

global noaa;

global JR;
global NP;
global CD;
global AE;
global MNE;
global CR;
global max1;
global max2;
global min1;
global min2;
global cvStore PopulationStore;
global NEStore;
global PopList;
global Dim;
global Population;
global lowfe;
global cv;

lowfe = 0;

SizePL=size(PopList);
Dim=SizePL(1,1);
SS=MNE/(NP-1);
%SS=1;

newpop;
%PopulationStore=Population;
%clock

calccv;
%clock
%cvStore=cv;
%NE=fgeneric('evaluations');
NE=fgeneric('evaluations');;
%clock
%clock
%cvStore=cv;

mincv=min(cv);
ftarget1 = fgeneric('ftarget');
Err=mincv-ftarget1;
%fprintf('Minimum at %f    Error at %f\n',mincv,Err);
%fprintf('Self organization began\n');
%clock
store=0;
loop=0;
NofC=1;
CH=[];
CHI=1;
%NEStore=NE;
%restart = 0;
NE1=fgeneric('evaluations');
while (mincv > ftarget1)% && (restart ~= 1)
   noaa=0;
   loop=loop+1;
   if loop==SS
      fprintf('Loop %d\nSearching clusters...\n',NE);
   end;
   NofC=1;
   ps(1)=1;
   for i=1:NP
      IsFar=1;
      j=1;
      for j=1:NofC
         x=Population(ps(j),:)-Population(i,:);
         for k=1:Dim
            x(k)=x(k)/(PopList(k,2)-PopList(k,1));
         end
         Dst=sqrt(x*x');
         if Dst<CD
            if cv(i)<cv(ps(j))
               ps(j)=i;
            end
            IsFar=0;
         end
      end
      if IsFar==1
         NofC=NofC+1;
         ps(NofC)=i;
      end
   end
   if NE-NE1+(NP-1)*NofC >= MNE
       break;
   end
   if loop==SS
       fprintf('...%d cluster found. Calculating jumps...\n',NofC);
   end;
   for i=1:NP
      mincv=cv(i);
      minpop=Population(i,:);
      for j=1:NofC
         if ps(j)~=i
            direct=Population(ps(j),:)-Population(i,:);
            for k = 1:Dim
               if rand >= CR
                  direct(k)=0;
               end
            end
            k=JR(1)+rand*(JR(2)-JR(1));
            pop=Population(i,:)+direct*k;
            for l=1:Dim
               pop(l)=CheckType(pop(l),PopList(l,:));
            end
            tcv=FitFnc(pop');
            if tcv<mincv
               mincv=tcv;
               minpop=pop;
            end
         end
      end
      NewP(i,:)=minpop;
      Newcv(i)=mincv;
   end
   minpop;
   Population=NewP;
   cv=Newcv;
   mincv=min(cv);maxcv=max(cv);
   Err=mincv-ftarget1;
%   HistPop1(NE)=mincv;
%   ClusterHist(NE)=NofC;
%   NE=NE+NP*NofC-NofC;
   NE=fgeneric('evaluations');
   store=store+1;
   if store==SS
      fprintf('Minimum at %f    Error at %f\n',mincv,Err);
      store=0;
      loop=0;
   end
%   CH(CHI) = NofC;
%   CHI = CHI + 1;
%   if CHI>40
%       if (CH(CHI - 1) == CH(CHI - 2)) && (CH(CHI - 1) == CH(CHI - 3)) && (CH(CHI - 1) < 4)
%           restart = 1;
%       end
%   end

%   PopulationStore=Population;
%   cvStore=cv;
%   NEStore=NE;
end
%clock

if (NE-NE1+(NP-1)*NofC >= MNE) && (NE-NE1<NP*2)
    lowfe = 1;
end
