Building a finite state machine