changing some for loops to declare loop counters outside