added caching and debug code