Fixed bug in grouping code