Improved kmeans implementation