#include <stdlib.h>
#include <stdio.h>

#include <termios.h>
#include <string.h>

static struct termios stored;
static char strTEST[]   = "TEST";
static char strCLIENT[] = "CLIENT";

void init(void)
{
    struct termios new;

    tcgetattr(0,&stored);

    memcpy(&new,&stored,sizeof(struct termios));

    /* Disable canonical mode, and set buffer size to 1 byte */
    new.c_lflag &= (~ICANON + ~ECHO);
    new.c_cc[VTIME] = 0;
    new.c_cc[VMIN] = 1;

    tcsetattr(0,TCSANOW,&new);
    return;
}

void done(void)
{
    tcsetattr(0,TCSANOW,&stored);
    return;
}

int main()
{
    char buffer;
    enum{START,T,E1,S,C,L,I,E2,N} state = START;

    init();

    while (1)
    {
        buffer = getchar();

        switch (buffer)
        {
            case 'C':
                state = C;
                break;
            case 'E':
                if (state == T)
                    state = E1;
                else if (state == I)
                    state = E2;
                else
                    state = START;
                break;
            case 'I':
                if (state == L)
                    state = I;
                else
                    state = START;
                break;
            case 'L':
                if (state == C)
                    state = L;
                else
                    state = START;
                break;
            case 'N':
                if (state == E2)
                    state = N;
                else
                    state = START;
                break;
            case 'S':
                if (state == E1)
                    state = S;
                else
                    state = START;
                break;
            case 'T':
                if (state == S)
                {
                    state = START;
                    printf("TEST");
                }
                else if (state == N)
                {
                    state = START;
                    printf("CLIENTSERVER\r");
                    done();
                    return 0;
                }
                else
                    state = T;
                break;
            default:
                state = START;
        }
    }
}

