A quick look and I see:
That’s going to run off the end of the array. You need to have a -1 in there…