Change to use a state-machine approach