I hate going to bed with bugs in my code. It has always bothered me so much. So I give up on debugging this off-by-one bug just before my last update, resolved myself to go to bed, brushed my teeth, turned out the lights, got in bed, and sat there for 5 minutes fuming that I had that bug.
Thankfully, a stroke of genius occured and I bolted out of bed, solved the problem, and now the function seems to work perfectly (at least with my test data). I love when that happens.