Refactored for less recursion and clarity
refactored for more clarity