Fixed off-by-one bug found by test cases