Fix some code that was running off the end of an array

This appears to fix #117 based on my tests. I'm actually kinda surprised this bug stayed hidden for so long.