
/**** LISTING 3 *******/

main()
{
    int get_event();
    ARG arg;

    init(&arg);

    /* the event loop */
    while (1)
    {
        driver(get_event(), &arg);
    }
}

/* Initialize the ARG structure */
int init(arg)
    ARG *arg;
{
    arg->cur_state = 1;
    arg->chan = 1;
}

/* Get an event - here it is from stdio */
int get_event()
{
    int ev;
    printf("Event: ");
    if (scanf("%d", &ev) != 1)
    {
        printf("\nCompleted\n");
        exit(0);
    }
    return (ev);
}

/* send the event through the state machine */
int driver(ev, arg)
    int ev;
    ARG *arg;
{
    register int curr = arg->cur_state;
    register int i,j;
    int (*func) ();

    /* find the state */

    for (i = 0; (curr != s_table[i].state || s_table[i].state == END); i++);

    if (s_table[i].state == END)
    {
        printf("Invalid State: %d\n",curr);
        return (-1);
    }

    /* find the event for this state */

    for (; (s_table[i].event != ev && s_table[i].state == curr); i++);

    if (s_table[i].state != curr)
    {
        /* uncomment printf if warning desired */
        /* printf("Invalid event: %d\n", ev);  */
        return (-2);
    }

    /* set the next state */

    arg->cur_state = s_table[i].n_state;

    /* execute the function list */

    for (j = 0; j < MAX_FUNCS; j++)
    {
        if ((func = *(s_table[i].flist[j])) != 0)
            (*func) (arg);
    }

    return (0);
}

