refactored to avoid a recursion and sideeffect