Do you have a limit on the number of fields you can use for grouping? If so, this can easily be done in the report itself, rather than having to code a lot of stuff for it. To do this, you set up a parameter for each group and do something like this:
Switch({?Group1 Param} = 'Country', {table.Country Field},
{?Group1 Param} = 'State', {table.State Field},
true, {table.Default Group Field})
You would then group on this formula instead of the specific fields.
In your code, you have to explicitly set the parameter values. I would try setting the record selection formula first and then set the parameters.
-Dell