Fix off-by-one error
Add test cases