Adjusted logic to make the statemachine easier to follow