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

#include "common.h"


int main(int argc, char *argv[]) {
int semid, shmid, res;
void *shared_mem;
ushort_t semValue;
struct sembuf theSemOp;
apothiki *theApothiki;
char resp[128];

/* Elegxos parametron */
if (argc < 2) {
	printf("Usage is: %s noumero_apothikis\n", argv[0]);
	exit(1);
}


/* Arxikopoihsh diamoirazomenhs mnhmhs kai shmaforwn */
if ((semid = semget(atoi(argv[1]), 3, 0)) == -1) {
	printf("Pou einai o apothikarios;\n");
	exit(1);
}
if ((shmid = shmget(atoi(argv[1]), sizeof(theApothiki), 0)) == -1) {
	printf("Pou einai o apothikarios;\n");
	exit(1);
}
if ((shared_mem = shmat(shmid, NULL, 0)) == NULL) {
	perror("attaching shmem");
	exit(1);
}
theApothiki = shared_mem;

printf("Ksekinaw...\n");
while (1) {
	printf("pata enter gia na fortoso, 0 gia na stamatiso: ");
	gets(resp);
	if (resp[0] == '0') break;

	sleep(rand() % 4); /* Diadromh mexri apothiki */
	printf("Eftasa apothiki...\n");
        /* down(empty) */
        theSemOp.sem_num = SEMNUM_APOTHIKI_EMPTY; theSemOp.sem_op = -1; theSemOp.sem_flg = 0;
        if (semop(semid, &theSemOp, (size_t)1) == -1) {perror("semop"); exit(1); }
        /* down(mutex) */
        theSemOp.sem_num = SEMNUM_APOTHIKI_MUTEX; theSemOp.sem_op = -1; theSemOp.sem_flg = 0;
        if (semop(semid, &theSemOp, (size_t)1) == -1) {perror("semop"); exit(1); }

	theApothiki->items[theApothiki->lastItem] = 'A' + (rand() % 26);
        printf("Voitha re vaggela gia to %d [%c] sto ksefortwma\n",
		theApothiki->lastItem,
		theApothiki->items[theApothiki->lastItem]);
	(theApothiki->lastItem) = (theApothiki->lastItem + 1) % SIZE_APOTHIKI;

        /* up(full) */
        theSemOp.sem_num = SEMNUM_APOTHIKI_FULL; theSemOp.sem_op = 1; theSemOp.sem_flg = 0;
        if (semop(semid, &theSemOp, (size_t)1) == -1) {perror("semop"); exit(1); }
        /* up(mutex) */
        theSemOp.sem_num = SEMNUM_APOTHIKI_MUTEX; theSemOp.sem_op = 1; theSemOp.sem_flg = 0;
        if (semop(semid, &theSemOp, (size_t)1) == -1) {perror("semop"); exit(1); }
	printf("Ksefortwsa, paw gia epomeno dromologio\n");
}
printf("Xeirofreno!\n");
return 0;
}

