#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

void print_choice(char *who, int choice);
int compare_choices(int my_choice, int other_choice); /*
	compare choices, return 0 on tie, 1 on my win, -1 on my loss */

int main(int argc, char *argv[]) {
int pipe1[2], pipe2[2];
pid_t opponent_pid;
int my_choice, other_choice, score = 0, tries = 0;
struct timeval tv;


if ((pipe(pipe1) == -1) || (pipe(pipe2) == -1)) {
	perror("Creating pipe");
	exit(1);
}

opponent_pid = fork();
if (opponent_pid == -1) {
	perror("Creating opponent");
	exit(1);
}

gettimeofday(&tv, NULL);
srand(tv.tv_usec);

if (opponent_pid == 0) { /* child */
	close(pipe1[0]);
	close(pipe2[1]);
	for (tries = 0; tries < 10; tries++) {
		my_choice = rand() % 3;
		print_choice("child", my_choice);
		write(pipe1[1], &my_choice, sizeof(int));
		read(pipe2[0], &other_choice, sizeof(int));
		print_choice("child->opponent's choice", other_choice);
		if (compare_choices(my_choice, other_choice) > 0) score++;
	}
	printf("child score: %d\n", score);
	close(pipe1[1]);
	close(pipe2[0]);
	return 0;
}
else { /* parent */
	close(pipe1[1]);
	close(pipe2[0]);
	for (tries = 0; tries < 10; tries++) {
		my_choice = rand() % 3;
		print_choice("parent", my_choice);
		read(pipe1[0], &other_choice, sizeof(int));
		write(pipe2[1], &my_choice, sizeof(int));
		print_choice("parent->opponent's choice", other_choice);
		if (compare_choices(my_choice, other_choice) > 0) score++;
	}
	printf("parent score: %d\n", score);
	close(pipe1[0]);
	close(pipe2[1]);
	wait(NULL);
}
return 0;
}

void print_choice(char *who, int choice) {
static char *descr[] = {"petra", "psalidi", "xarti", "AKYROS KWDIKOS"};
char *theDesc;

if ((choice >= 0) && (choice <= 2))
	theDesc = descr[choice];
else
	theDesc = descr[3];
printf("%s: %s\n", who, theDesc);
}


int compare_choices(int my_choice, int other_choice) {

if (my_choice == other_choice) return 0;
else if ((my_choice == 0 && other_choice == 1) ||
	 (my_choice == 1 && other_choice == 2) ||
	 (my_choice == 2 && other_choice == 0))
	return 1;
else return -1;
}


