Added average function and minor code cleanup