Further speed improvements by putting the getmed function forward in the code