Fix a potential error in the previous commit caused by the use of a separate index variable. Thanks to dmethvin for the review.