Some cleanup, improved statemachine