Optimized for loops by changing for-each loops to use an index i.

Needs to be tested, but looks right.