recursive implementation of grouping