Refactor state machine for simplicity and easier operation

See comments.