Fix a number of off-by-one logic errors