/*
----------------------------------------------------------------
Y. CIURLIK & A. DUCHENE - Projet Compil - M1GMI
-------------------------------------------------------------------
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

void triSelection(int tab[], int n) {
	int i, j, x, min;
	for(i = 0; i < (n - 1); i++) {
		min = i;
		for(j = (i + 1); j < n; j++) {
			if(tab[j] < tab[min]) {
				min = j;
			}
		}
		if(min != i) {
			x = tab[i];
			tab[i] = tab[min];
			tab[min] = x;
		}
	}
}

int main (int argc, char *argv[]) {

	FILE *file;
	char **mots;		// Ensemble de mots a chercher
	int alpha;
	char buffer[256]; 
	int i;

	if(argc<4) {
		printf("Generateur de motif dans le fichier fic.txt\n");
		printf("Usage : %s fic.txt taille(Mo) motif1 [motif2] [motif3] ...\n",argv[0]);
		exit(1);
	}	

	int nbMot = argc - 3;
	char *dest = argv[1];
	int size = atoi(argv[2]);
	
	srand(time(NULL));
	char car[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
	'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
	mots = (char**) malloc(sizeof(char*)*nbMot);
	printf("Ajout de %d mot(s) dans le fichier\n",nbMot);
	for(alpha=3;alpha<argc;alpha++){
		strcpy(buffer,argv[alpha]);
		mots[alpha-3] = (char*) malloc(sizeof(char)*(1+strlen(buffer)));
		strcpy(mots[alpha-3], buffer);
	}
	int pos[nbMot];
	for (i = 0; i < nbMot; i++) {
		pos[i] = (int) (rand() / (double) RAND_MAX * ((size*1000000)-10));
	}
	triSelection(pos, nbMot);
	file = fopen(dest, "w");
	int nbAlea, nbChar;
	for (nbChar = 0, i = 0; nbChar * sizeof(char) < (size*1000000); ) {
		if (pos[i] == nbChar) {
			printf("Ajout du mot %s en position %d dans le texte\n",mots[i],pos[i]);
			fprintf(file, "%s", mots[i]);
			nbChar += strlen(mots[i]);
			if (i < nbMot) {
				i++;
			}
		} else {
			nbAlea = (int)(rand() / (double)RAND_MAX * (sizeof(car) - 1));
			fprintf(file, "%c", car[nbAlea]);
			nbChar++;
		}
	}
	fclose(file);
	printf("Le fichier %s a ete correctement genere\n",dest);
	return 0;
}
