function  newpop=repair_cerveza(t,pop,value,rad,TempInit)

% REPAIR_CERVEZA Repairs the genes of the beer problem	 
%
% NEW_POP=REPAIR_CERVEZA(T,POP,RANGE,rad,TempInit)
%
%
% It checks that all the genes of POP are between RANGE(1)<= POP <= RANGE(2), and if 
% not, it moves the incorrect values to the closest RANGE. Additionally it uses the gradient to join 
% groups.
% TempInit is the initial temperature
% T is not used but needs to be an input parameter to mantain the header for the FUNGEN functions
%
% See also IS_NEW, GA_REPAIR


% APRENDIZAJE AUTOMÁTICO (G. Pajares y J. M. de la Cruz, Eds.)
% Editorial: RA-MA
% Capítulo 9: El Aprendizaje con Algoritmos Genéticos
% Autores: Bonifacio de Andres y Toro


newpop=pop;
%newpop{:},
[r,c]=size(pop);
for i=1:r   
   newpopi=newpop{i};
   l=find(newpopi(1,:)>value(2));
	newpopi(1,l)=value(2);
	l=find(newpopi(1,:)<value(1));
   newpopi(1,l)=value(1);
   newpopi(1,:)=round(10*newpopi(1,:))/10;
   newpopi(1,1)=TempInit;
   % Parte del gradiente
   newpop{i}=improve(newpopi,rad);
end
%newpop{:},pause

function newpop=improve(pop,rad)

newpop=pop;
if size(pop,2)>2
	m=atan2(diff(pop(1,:)),pop(2,1:end-1));
	n=abs(diff(m));
	%i=find(n>pi);  % No puede ser, una grafica no puede ir para atras
	%n(i)=n(i)-pi;
   menor=find(n<rad);
   if ~isempty(menor)
      group{1}=menor(1);
      l=1;
      for j=2:length(menor)
         if group{l}(end)==(menor(j)-1)
            group{l}(end+1)=menor(j);
         else
            l=l+1;
            group{l}=menor(j);
         end
      end
      for j=1:length(group)
         i=min(group{j})-j+1;;      
         pop=[pop(1,1:i),pop(1,i+2:end);pop(2,1:i-1),sum(pop(2,i:i+1)),pop(2,i+2:end)];
      end
      newpop=improve(pop,rad);
   end
   
end

















