Especially the buildGroups function is too long and too stream-of conscious. It should be split into multiple functions