Fix including one more than max.

Also check only when the value is changed, and add sanity assert.