Improved algorithm performance and caching. Fixed some bugs.