Sort-of fixed outer scope references in for loops

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