
function [Fbest,BestChart,BestFitness,farmlayout,farmlayout_NA]=HGSA(N, ElitistCheck, min_flag, Rpower,wf,max_it,t,NA_type,tn,wt,algorithmDir)

 
Rnorm=2; 
 
%get allowable range and dimension of the test function.

D = wf.turbine_num; down = 1;up = wf.rows *wf.cols;

BestChart=zeros(max_it,1);
BestFitness=zeros(max_it,1);
farmlayout = zeros(max_it,wf.rows*wf.cols);
farmlayout_NA = zeros(max_it,wf.rows*wf.cols);

%random initialization for agents.
% X=initialization(D,N,up,down); 
[X,lu] = windfarm_init(N, wf.turbine_num,wf);
Fbest_individual = inf.*ones(1,D);
%create the best so far chart and average fitnesses chart.
BestChart=[];

V=zeros(N,D);


for iteration = 1:max_it
    
    %Checking allowable range. 
%     X=space_bound(X,up,down); 
    X = windfarm_constraint(X, wf.NA_loc, D,down,up);

    %Evaluation of agents. 
    [fitness,power_order]= wf_fitness(wf,X);
    
    
    if min_flag==1
    [best, best_idx]=min(fitness); %minimization.
    else
    [best, best_idx]=max(fitness); %maximization.
    end        
    
    if iteration==1
       Fbest=best;Fbest_individual = X(best_idx,:);
    end
    if min_flag==1
      if best<Fbest  %minimization.
       Fbest=best;Fbest_individual = X(best_idx,:);
      end
    else 
      if best>Fbest  %maximization
       Fbest=best;
      end
    end
	
BestChart=[BestChart; Fbest];



[M]=massCalculation(fitness,min_flag); 

G=HGconstant(iteration,max_it); 


a=HGfield(M,X,G,Rnorm,Rpower,ElitistCheck,iteration,max_it,Fbest_individual);



[X,V]=move(X,a,V);

BestChart(iteration) = Fbest / wf.power_total;
BestFitness=Fbest;
[best_farmlayout,best_farmlayout_NA]  = gene_layout_by_indices_one(wf,Fbest_individual);
farmlayout(iteration,:) = best_farmlayout;
farmlayout_NA(iteration,:) = best_farmlayout_NA;

% fprintf('%s NA %d Turbine Num:%d Wind %s run: %d iteration: %d  eta %f fitness %f\n',algorithmDir,NA_type,tn,wt,t,iteration,(Fbest / wf.power_total),Fbest)
end %iteration

