Refactor use a state machine pattern