Move threading lock to outer scope
Rearrange recursion base case