Added query caching and did some refactoring