Remove unused imports
Improve grouping function