refactor averaging code