Improved algorithm.