finalised base code for average calculation