Fix loop end condition.

Note: This code appears to be untested.