Refactor output code.
Add diagnostic output for grouping.