Rewrite statemachine

Send pull request to myself??