Adding the state machine and reorganize the code