refactoring horrible recursion to make it less horrible