fixed bug introduced by moving the loop variables out of the for loops