Search the forum (and/or Google) for "finite state machine".