refactored algorithm