remove recursion and move its functionality to the loop.