replaced recursion with loops