refine flatten and group