This whole function is a convoluted way of doing memoization.