function y = kmeans(X, k, verbose)
% function y = kmeans(X, k, verbose)
% 
% Finds k cluster in data X

if nargin < 3
	verbose = 0;
end

[n,m] = size(X);
max_iter = 1000;

% Initialisieren mit zufaelligen Beispielen
%i = randperm(n);
%Means_old = X(i(1:k),:);

% Initialisieren mit zufaelligen Punkten im Wertebereich der Daten
Xmin = min(X);
Xmax = max(X);
Means_old = rand(k, m).*repmat(Xmax - Xmin, k, 1) + repmat(Xmin, k, 1);

if verbose && m == 2
    plot(Means_old(:,1), Means_old(:,2), '*');
end

for i = 1:max_iter
    R = findMapping(X, Means_old);
    Means = findMeans(X, R);
    if sum(sum((Means_old - Means).^2)) < 1e-8*k*m
        break
    end
    Means_old = Means;
end
[foo, y] = max(R');
y = y';

if verbose && m == 2
    plot(Means(:,1), Means(:,2), '*');
end
