#include <stdio.h>
#include <string.h>
#include <pthread.h>


#define MAXSIZE 50
#define TABLESIZE 10
/*
 * Semaphoring - A small test case of a command interpreter
 *
 * By Andreas Fugl
 *
 * TODO: Try again with forking processes from the main loop.
 *
 */

/* Function primitives */

void acq();
void inittable();
void showtable();
void showhelp();
int getkbd(char *s);
/* static void startthread(); */
/* static void *threadfn(void *arg); */

/* External variables */

int stable[TABLESIZE];
static pthread_t tid;

main()
{
    char command[MAXSIZE];

    inittable();

    printf("semaphoring 0.1.\n");
    printf("sema> ");
    
    /* Command decision */
    while (getkbd(command)) { 
        if (!strcmp(command,"1"))
            printf("command 1\n");
        else if (!strcmp(command,"acq"))
            acq();                
        else if (!strcmp(command,"h") 
                || !strcmp(command,"help")
                || !strcmp(command,"?"))
            showhelp();
        else if (!strcmp(command,"init")) {    
            inittable(); 
            printf("Semaphore table initialized (Size %d)\n",TABLESIZE);
        }
        else if (!strcmp(command,"q") || 
                !strcmp(command,"quit")) {
            /* printf("exiting...\n"); */
            return 0; 
        }
        else if (!strcmp(command,"show"))
            showtable();
        else
            printf("%s: no such command (type \"h\" for help)\n",command);

        printf("sema> ");
    }
}

void inittable()
{
    extern stable[];
    int i;

    for (i=0; i<TABLESIZE; ++i) {
        stable[i] = 0;
    }
}

void showtable()
{
    extern stable[];
    int i;

    printf("Semaphore table:\n");
    
    for (i=0; i<TABLESIZE; ++i) {
        printf("\t%d\t%d\n",i,stable[i]);
        /*if (stable[i] == 0)
            printf("%s\n","unused");
        else
            printf("%s\n","in use");*/
    }
}

void showhelp()
{
    printf("Commands may be abbreviated. Commands are: \n\n");

    printf("help\t\tshow this help message\n");
    printf("init\t\tinit the semaphore table\n");
    printf("quit\t\texit semaphoring\n");
    printf("show\t\tshow the semaphore table\n");
}

void acq()
{
    
    char value[10];
    char semp[10];
    int procid;
    int sempid;
    
    printf("Enter process ID to simulate: ");
    getkbd(value);
    sscanf(value,"%d",&procid);    

    printf("Enter key of semaphore to acquire: ");
    getkbd(semp);
    sscanf(semp,"%d",&sempid);    
}

void *threadfn(void *arg)
{
   pthread_exit(NULL); 
}

static void startthread(void)
{
    printf("%s\n","hej");
    pthread_create(&tid,NULL,threadfn,NULL); 

    return;
}


/*
 * Takes pointer to string, and fills it up with character input until
 * NewLine, then return. 
 *
 */
int getkbd(char *s)
{
    int i,c;
    
    for (i=0; i<MAXSIZE && (c=getchar()) != EOF && c !='\n'; ++i) {
        s[i] = c;
    }
    s[i] = '\0';

    return 1;
}
