Refactored algorithm.