/****************************************************************/
/* sem.h                                                        */
/* Justin Hartman                                               */
/* EECS 338 - Spring 2003                                       */
/* Assignment 5                                                 */
/****************************************************************/

/****************************************************************/
/* Acknowledgment:                                              */
/* Most of this code was written by and borrowed from the       */
/* computer science department at CWRU                          */
/* http://art.cwru.edu/338/example.shm.sems.html                */
/****************************************************************/

/****************************************************************/
/* Written in Microsoft Visual C++ .NET                         */
/* Compiled and executed on CWRU's EECS department              */
/* lab's (Olin 404.5) SUN boxes using SSH and                   */
/* secure FTP                                                   */
/****************************************************************/

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/errno.h>
#include <sys/time.h>
#include <wait.h>
#include <time.h>
#include <math.h>

#define bool short
#define true 1
#define false 0

#define SKIERCOUNT	16	/* Number of skiers */
#define RIDESMAX	40	/* Number of rides for each skier */

union semun {
	int val;
	struct semid_ds *buf;
	ushort *array;
};

/* Format a string to reflect the current time */
void mktimestr(char *timebuf)
{
	time_t t;
	struct tm* tp;

	t = time(0);
	tp = localtime(&t);
	strftime(timebuf, 16, "%X", tp);
}

/* Return a random int between 0 and 5 inclusive */
int rand0to5 ()
{
    short randval = 6;

    while (randval > 5)
        randval = (short)floor((rand() / (RAND_MAX * 1.0)) * 6);
    return (int)randval;
}

/* The wait primitive for the semaphores */
void P(int semid, int semaphore)
{
    struct sembuf psembuf;

    psembuf.sem_op = -1;
    psembuf.sem_flg = 0;
    psembuf.sem_num = semaphore;
    semop(semid,&psembuf,1);
    return;
}

/* The signal primitive for the semaphores */
void V(int semid, int semaphore)
{
    struct sembuf vsembuf;

    vsembuf.sem_op = 1;
    vsembuf.sem_flg = 0;
    vsembuf.sem_num = semaphore;
    semop(semid,&vsembuf,1);
    return;
}