Fix including one more than max.

Also check only when the value is changed, and add sanity assert.
Merge pull request #8 from Thynix/off-by-one

Fix including one more than max.