final grouping and writing