#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "usersem.h"

int main(int argc, char *argv[])
{
	struct futex *futex;
	int fd;
	void *map;

	if (argc != 4) {
		fprintf(stderr, "Usage: test <file> <offset> show|init|up|down|mem\n");
		exit(1);
	}
	fd = open(argv[1], O_RDWR);
	if (fd < 0) {
		perror("opening file");
		exit(1);
	}
	map = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if (map == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}

	if (futex_region(map, 4096) != 0) {
		perror("futex_region");
		exit(1);
	}
	futex = map + atoi(argv[2]);
	if (strcmp(argv[3], "init") == 0)
		futex_init(futex);
	else if (strcmp(argv[3], "up") == 0) {
		if (futex_up(futex) != 0) {
			perror("futex_up");
			exit(1);
		}
	} else if (strcmp(argv[3], "down") == 0) {
		if (futex_down(futex) != 0) {
			perror("futex_down");
			exit(1);
		}
	} else if (strcmp(argv[3], "mem") == 0) {
		struct futex myfutex;
		futex_init(&myfutex);
		futex_down(&myfutex);
		futex_down(&myfutex);
	} else if (strcmp(argv[3], "show") == 0) {
		printf("count = %i\n", futex->count);
	}
	exit(0);
}
	
