Refactor kmeans into readable chunks