Commits ready for merge

I've made agreement with Yifan.
The state machine is almost done (2 handles left).
Currently the coverage is only 41.3%. Needs more tests.