refactored to use recursion