Fix a bug in next state caching. Add simple simulation test to detect
such bugs.
Merge branch 'develop'