replaced for loop with function