Fixed off-by-one error and added additional test case exposing it.