Fix various off-by-one errors