Refactors code into method to make it ready for recursion.