Moved loop counter to outside of loop