restructure agg function