modification to grouping algorithm