/*
 * Autor: Carles Pina i Estany <carles arroba pinux.info>
 * Data: Març 2004
 * Llicència: GPL 2.0 o posterior
 * Més informació: http://pinux.info/utils#cadenciatecleo
 */

/*
 * PER COMPILAR: gcc -lncurses cadenciatecleo.c
 */


#include <ncurses.h>
#include <sys/timeb.h>

#define INDIVIDUAL 15
#define ABSOLUT 3


int apren ();

int main(int argc, char **argv)
{
	if (argc!=2) {
		printf("Ús: %s 1: apren\n",argv[0]);
		printf("Ús: %s 0: comprova\n",argv[0]);
		exit(2);
	}
	
	initscr();
	noecho();
	
	if (strncmp(argv[1],"1",1)==0) {
		apren();
	}
	if (strncmp(argv[1],"0",1)==0) {
		comprova();
	}
	endwin();
}

int apren () {
	FILE *fp;

	struct timeb ant;
	struct timeb act;

	int i=0;
	int car;
	int mseg;
	
	fp=fopen("sortida.txt","w"); 
	car='a';
	
	printw("Escriu per aprendre: ");
	
	ftime(&ant);

	while(car!='\n') {
		car=getch();
		ftime(&act);
		mseg=(act.time-ant.time)*1000+(act.millitm-ant.millitm);
		if (i>1) {		//el primer cop no agafem temps
			fprintf(fp,"%d ",mseg);
		}
		ant=act;
		i++;
	}
	fprintf(fp,"\n");
	fclose(fp);
	return 0;
}


int comprova () {
	FILE *fp;

	struct timeb ant;
	struct timeb act;
	int erronies=0;
	int percent;

	int i=0;
	int car;
	int teclejat;
	int guardat;
	
	printw("Escriu contrasenya i prem intro per comprovar\n");


	fp=fopen("sortida.txt","r"); 
	car='a';
	
	ftime(&ant);
	while(car!='\n') {
		car=getch();
		ftime(&act);
		teclejat=(act.time-ant.time)*1000+(act.millitm-ant.millitm);
		if (i>1) {		//el primer no comprovem temps
			fscanf(fp,"%d",&guardat);
			percent=percentatge(guardat,teclejat);
			if (abs(percent-100)>INDIVIDUAL) {
				erronies++;
				//printw("%d* - ",percent);
			}
		/*	else {
				printw("%d - ",percent);
			}*/
		}
		ant=act;
		i++;
	}
	fclose(fp);
	printw("Erronies: %d\n",erronies);
	if (erronies <= ABSOLUT) {
		printw("Ok!\n");
	}
	else {
		printw("Login incorrect\n");
	}
	getch();
	return 0;
}

int percentatge(int guardat,int teclejat) {
	return(abs((guardat*100)/teclejat));
}

