improved grouping and merging