some refactoring and basic caching