Fixed the caching, added comments and debug logging