Use finite-state machine solution from fuwutu.