Add support for grouping by activity

This also fixes a bug in the grouping.