fixed infinite loop bug by adding yet another function inside a function, problem was caused by for loop having only one scope not one per iteration