Cleaned up average calculation code