Can this be done with a state machine

YES

For extra information and examples look at

you might benefit from studying state machines. Here is a small introduction to the topic: Yet another Finite State Machine introduction