function stuff = kmtrain(Xin,yin,nmean)

if nargin<3  nmean = 8;  end; % make eight means

[n,d] = size(Xin);

% -- initialize the means to one point from each class
for k=1:nmean
    mdx = find(yin == (k-1));
    means(k,:) = Xin(mdx(ceil(rand*length(mdx))),:);
end;

% -- do the training
lmeans = zeros(nmean,d);
cont = 1;
soft_assn = [];
lsoft_assn = ones(1,n);

while(cont)

    %Estep -- assign each sample to a mean
    for i=1:n
        dmat = [Xin(i,:);means];
        d = dist(dmat');
        [a,b] = min(d(1,2:size(d,2)));
        soft_assn(i) = b;
    end;

    % (check to see if there are no changes)
    if (sum(abs(lsoft_assn-soft_assn)) == 0)
        cont = 0;
    else
        % (report on progress)
        fprintf('%d points changed\n',...
            sum(abs(lsoft_assn-soft_assn)));
        lsoft_assn = soft_assn;
        
        %Mstep -- change the means based on data
        for j=1:nmean
            hdx = find(yin == j-1);    %labled "j"
            idx = find(soft_assn==j);  %assigned "j"
            
            % mean becomes mean of properly labled
            %  points in the set
            jdx = intersect(hdx,idx);
            tassn(j) = length(jdx);
            if (~isempty(jdx))
                means(j,:) = mean(Xin(jdx,:),1);
            else
                fprintf('none were assigned to %d\n',j); 
            end;
        end;
        tassn
    end;        
end;

stuff{1} = means;
stuff{2} = soft_assn;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% -- find the distance between a review and a mean
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dist = distance(rev,mean)
dist = sqrt(sum((rev-mean).^2));