updated centroid code as function