generalize defrag_state()
Currently defrag_state() has the undocumented requirement that the new number should be smaller than the old one.
To allow users to renumber states arbitrarily we could detect cases where that's not true, and use a slightly slower implementation.