refactoring k-means code