Adding averaging subroutine