Improvements to speed of algorithm