Improvements to algorithm