memoization

I've fixed the broken test, reapplied all commits that were reverted and squashed them into one.
Hope everything goes well this time.
Sorry for the trouble.