Added var scoping to the for loops