Move aggregation code into separate procedure