Fix a out-of-range bug (that was also a mistake in the code)