#include "utils.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "window.h"

FILE *open_file(char *filename, char *mode){
	FILE *fin=NULL;
	fin=fopen(filename,mode);
	if (!fin) {
		perror(filename);
		exit(errno);
	}
	return fin;
}

void *dmalloc(size_t size){
	void *res=malloc(size);
	if (!res) {
		perror("Memory allocation failed!");
		exit(errno);
	}
}

void dfree(void *data){
	free(data);
}


void reset(void *data, size_t size) {
	memset(data,0,size);
}

void init_random_generator(){
	srand(time(NULL));
}

int d20(){
	return dice(20,1);
}

int d6(int n){
	return dice(6,n);
}

int dice(int faces, int n){
	int res=0, i;
	for(i=0; i<n ; i++)
		res+=randint(1,faces);
	return res;
}

int randint(int bt, int tp){
	return bt+rand()%(tp-bt+1);
}

char *random_name(){
	int line;
	char *buf=dmalloc(sizeof(char)*MAX_NAME_LEN);
	FILE *fin=open_file(NAMES_FILE,"r");
	fscanf(fin,"%d\n", &line);
	for(line=randint(1,line); line>0; line--)
		fgets(buf, MAX_NAME_LEN, fin);
	fgets(buf, MAX_NAME_LEN, fin);
	fclose(fin);
	buf[strlen(buf)-1]='\0';
	return buf;
}


#ifdef TEST_UTILS
#include <stdio.h>
int main(){
	int i;
	init_random_generator();
	
	printf("d20: ");
	for(i=0; i<30; i++)
		printf("%d ", d20());
	printf("\n");
	
	printf("3d6: ");
	for(i=0; i<30; i++)
		printf("%d ", d6(3));
	printf("\n");

	printf("Randint(1,i): ");
	for(i=2; i<30; i++)
		printf("%d ", randint(1,i));
	printf("\n");
	
	printf("random names:\n");
	for(i=0; i<30; i++){
		char *name=random_name();
		printf("%s\n", name);
		dfree(name);
	}
	printf("End of \"utils.c\" test\n");
}

#endif /* TEST_UTILS */
