#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.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 arxikesTimes[3] = {0, SIZE_APOTHIKI, 1};
union semun arg;
struct sembuf theSemOp;
apothiki *theApothiki;

/* 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) {
	perror("Anoigma shmaforwn apothikis");
	exit(1);
}
if ((shmid = shmget(atoi(argv[1]), sizeof(apothiki), 0)) == -1) {
	perror("Anoigma diamoirazomenhs mnhmhs apothikis\n");
	exit(1);
}
if ((shared_mem = shmat(shmid, NULL, 0)) == NULL) {
	perror("attaching shmem");
	exit(1);
}
theApothiki = shared_mem;
theApothiki->firstItem = theApothiki->lastItem = 0;

arg.array = arxikesTimes;
if (semctl(semid, 0, SETALL, arg) == -1) {
	perror("Getting values");
	exit(1);
}


while (1) {
	/* down(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); }
	/* 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); }
	
	printf("Vale re mitso to %d [%c] sthn apothiki\n",
		theApothiki->firstItem,
		theApothiki->items[theApothiki->firstItem]);

	theApothiki->firstItem = (theApothiki->firstItem + 1) % SIZE_APOTHIKI;
	/* up(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); }
	/* 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); }
}
return 0;
}

