Fixed a logical error in a for loop