got rid of recursion, moved to loop