Fix issue causing exponential explosion

There was a generator expression causing exponential explosion with growing number of nested groups. I rewrote that part to avoid it.