implemented clustering part of algorithm