function [centroids, energy,centMap] = kIt(k,centroids,data,boxExtreme)
energy = realmax;
iterations = 0;

while(  (iterations < 30)  )
	iterations = iterations +1;
	lastEnergy = energy;
	energy =0;
	for(i=1:size(data,1))
		[nearest,distance] = findClosest2(centroids, data(i,:));
		centMap(i)=nearest;
		energy = energy + distance;
	end
	centDivide = zeros(k,1);
	% 	centDivide =centDivide +1;%add one for the existing centroid
	centroids = zeros(k, size(data,2));
	for(i=1:size(data,1))
		index = centMap(i);
		centroids(index, :) = centroids(index,:) + data(i,:);
		centDivide(index) = centDivide(index) +1;
	end


	%might optimize this in matrix notation
	for(i=1:k)
		if(centDivide(i) == 0)
			randMult = boxExtreme(2,1) - boxExtreme(1,1); 
			randAdjust = boxExtreme(1,1); 
			centroids(i,:) = randMult .* rand(1, size( boxExtreme,2 ) ) + randAdjust; 
		else
			centroids(i,:) = centroids(i,:) / centDivide(i);
		end
	end
end
