removing recursive function call and replacing with a loop