refactored with caching improvements