recursion and some refactoring