This is "yet another state machine" implementation, but un Javascript.