refactored algorithm, implemented without channels