Refactored to use recursion.