fix boundary bugs in a couple of for-loops