Finish the new implementation of state machine. But not been unittested.