function [ c, ptoc ] = km ( dim, n, p, k )

%% KM carries out the K-Means algorithm.
%

%
%  Initialize the cluster centers.
%
  c = kmeans_initialize ( dim, n, p, k );
%
%  Repeatedly update clusters and centers til no change.
%
  v = -1;
  while ( 1 )

    ptoc = kmeans_update_clusters ( dim, n, p, k, c );

    c = kmeans_update_centers ( dim, n, p, k, ptoc );

    v_old = v;
    v = kmeans_variance ( dim, n, p, k, c, ptoc );

    if ( v == v_old )
      break
    end

  end

  return
end

  
