merged jakers implementation of yxu's grouping algorithm