Nest and sort data and minor refactoring.