refactoring the recursive functions