Implemented caching and fixed off by one error