refactored for memoization