improved clustering code