Fix off by one error and nil pointer dereference.