// http://www.thegeekstuff.com/2013/01/c-argc-argv/
// C argc and argv Examples to Parse Command Line Arguments
// Per debugar: nemiver t6_el_elegido t6_g00.csv
#include <stdio.h>
#include <time.h>	// time()
#include <stdlib.h>	// rand(), srand()

#define MAX_SIZE	200

int main (int argc, char *argv[]) {
	FILE *fp;
	char line[MAX_SIZE];
	char nom[MAX_SIZE];
	char cognom[MAX_SIZE];
	int total = -1, el_elegido, err, i;

	if (argc!=2) {
		printf("S'esperava 1 argument enlloc de %d.\n", argc-1);
		return -1;
	}

	fp = fopen(argv[1], "r");
	if (fp==NULL) {
		printf("Error al intentar obrir fitxer %s.\nSegur que existeix?\n", argv[1]);
		return -1;
	}

	while((err=fscanf(fp, "%[^\n]%*c", line)) != EOF) { // Parentesis!!!
		// Al ser un fscanf, i no un scanf el "%*c" podria
		// substituir-se per "\n".
		total++;
	}
	fclose(fp);

	printf("Total alumnes: %d\n", total);

	srand( (unsigned)time( NULL ) );
	el_elegido = (rand() % total)+2; // linea donde esta el elegido
	printf("Linea donde esta el elegido: %d\n", el_elegido);

	fp = fopen(argv[1], "r");
	if (fp==NULL) {
		printf("Error al intentar obrir fitxer %s per segon cop.\n", argv[1]);
		return -1;
	}

	for(i=0; i<el_elegido; i++) {
		fscanf(fp, "%[^,],%[^,],%*[^\n]%*c", nom, cognom);
	}
	printf("El elegido es: %s %s.\n", nom, cognom);

	fclose(fp);

	return 0;
}

