Refactored the main algorithm.