Minor but it is a bit odd having groups.iterator().next multiple times. Consolidate?