Sort-of fixed outer scope references in for loops

I had no idea what i was doing, but this one seems to work.