## Author: M. Turhan ÇOBAN
## Created: 2021-06-20
## set_genetic

function retval = set_genetic(fx,xmin,xmax,POPSIZE,MAXGENS,ngene,PXOVER,PMUTATION)
  N=64;
  N1 = 9223372036854775807;
  #    POPSIZE; //population size
	#    MAXGENS; //maximum number of generations;
	#    NVARS;   //number of independent variables of function
  #    ngene;        //number of genes in each variable
	#    PXOVER; probability of crossover;
  #    PMUTATION; proportion of mutated variables
  #    NBreeder; Number of survivors in a generation
  #    Best;  The best genotype1 in the population
  #    Population[];
  genetic1.POPSIZE=POPSIZE;  
  genetic1.MAXGENS=MAXGENS; 
  genetic1.xmin=xmin;
  genetic1.xmax=xmax;
  genetic1.ngene=ngene;
  genetic1.PXOVER=PXOVER;
  genetic1.PMUTATION=PMUTATION;
  genetic1.f=fx; 
  genetic1.ibest=1;
  genetic1.Fbest=1.0;
  genetic1.iworst=1;
  genetic1.Fworst=1.0;
  genetic1.RFbest=1.0;
  # set initial population
  maximum=-realmax;
  minimum=realmax;

  for i=1:POPSIZE
      for j=1:genetic1.ngene
       r1=rand;
       xp=N1*r1;
       xx1=double(genetic1.xmin(1,j)+xp*(genetic1.xmax(1,j)-genetic1.xmin(1,j))/N1);
       # fprintf("xp = %i xx1 = %i i = %i xmin %i xmax %i r1 %i \n",xp,xx1,i,genetic1.xmin(1,j),genetic1.xmax(1,j),r1);
       genetic1.genotype(i).x(1,j)=xx1;
       xx=double_to_binary (xx1,genetic1.xmin(1,j),genetic1.xmax(1,j));
       genetic1.genotype(i).b(j,:)=xx;
     endfor
     genetic1.genotype(i).y=genetic1.f(genetic1.genotype(i).x);
     if genetic1.genotype(i).y>maximum
            maximum=genetic1.genotype(i).y;
            genetic1.Fbest=genetic1.genotype(i).y;
            genetic1.ibest=i;
     endif
     if genetic1.genotype(i).y<minimum
            minimum=genetic1.genotype(i).y;
            genetic1.Fworst=genetic1.genotype(i).y;
            genetic1.iworst=i;
     endif
  endfor  # i=1:POPSIZE
  for i=1:POPSIZE
    genetic1.genotype(i).RFitness=(genetic1.genotype(i).y- genetic1.Fworst)/(genetic1.Fbest-genetic1.Fworst);
  endfor  # i=1:POPSIZE
    total=0.0;
   for i=1:POPSIZE
    genetic1.genotype(i).RFitness=(genetic1.genotype(i).y- genetic1.Fworst)/(genetic1.Fbest-genetic1.Fworst);
      total+=genetic1.genotype(i).RFitness;
    endfor  # i=1:POPSIZE 
    for i=1:POPSIZE
        if i==1 
          genetic1.genotype(i).RCFitness=genetic1.genotype(i).RFitness/total;
        else
          genetic1.genotype(i).RCFitness=genetic1.genotype(i-1).RCFitness+genetic1.genotype(i).RFitness/total;
        endif 
     endfor 
  genetic1.RFbest=genetic1.genotype( genetic1.ibest).RFitness;
  genetic1.RFworst=genetic1.genotype( genetic1.iworst).RFitness;
  retval =genetic1;  
endfunction