refactored algo