This loop figures out up to what level we need to create groups based on the definition level.
When everything is optional there are no consecutive levels with the same value, if there are required fields they will have the same value as the previous one.
In the case of all required fields, they do not require a definition level. Which means d will be 0 for all levels.
Before I was stoping when d was greater than current (ignoring if the next has the same value)
Now I'm stoping when d is greater or equal to the next which should take care of having several time the same value.
I will add more tests.
We did not see it before because we rarely use required.