#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<stdint.h>
#include<assert.h>
#include "helpers.h"
#include "helpers.c"

uint64_t shots = 0,
		 shots_in = 0;

double pi = 0, t1;
sigset_t inset, quiset, alset;


void int_handler(int){
	alarm(0);
	sigprocmask(SIG_BLOCK, &inset, NULL);
	char c;
	printf("Le programme tourne depuis %f secondes, voulez-vous vraiment l'arrêter ? (O)ui / (N)on", tstamp() - t1);
	c = getchar();
	if (c == 'O' || c == 'o' || c == 'Y' || c == 'y'){
		exit(0);
	}
	else{
		return;
		sigprocmask(SIG_UNBLOCK, &inset, NULL);
		alarm(5);
	}
}

void alarm_handler(int){
	sigprocmask(SIG_BLOCK, &alset, NULL);
	printf("Valeur de pi en cours = %f\n", pi);
	printf("Nombre de tirs effectués = %f\n", (double) shots);
	alarm(5);
	sigprocmask(SIG_UNBLOCK, &alset, NULL);
}

void quit_handler(int){
	alarm(0);
	sigprocmask(SIG_BLOCK, &quiset, NULL);
	shots = 0;
	shots_in = 0;
	t1 = tstamp();
	sigprocmask(SIG_UNBLOCK, &quiset, NULL);
	alarm(5);
}

int main(int argc,char * argv[])
{
	double x,y;
	t1 = tstamp();
	alarm(5);
	sigaddset(&alset, SIGINT);
	sigaddset(&alset, SIGQUIT);
	sigaddset(&inset, SIGALRM);
	sigaddset(&inset, SIGQUIT);
	sigaddset(&quiset, SIGINT);
	sigaddset(&quiset, SIGALRM);
	set_signal_handler(SIGALRM, &alarm_handler);
        set_signal_handler(SIGINT, &int_handler);	
	set_signal_handler(SIGQUIT, &quit_handler); 
	while(1){
		x = ((double)rand())/(double)RAND_MAX;
		y = ((double)rand())/(double)RAND_MAX;
		shots ++;
		if ((x*x+y*y) <= 1) 
			shots_in ++;
		pi = shots_in * 1.0 / shots * 4;
	}
}
