Added code from cachemean and added comments