Fixed bug: had forgotten to change to the momoization method in one place
Some refactoring.