#define _DEFAULT_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>

#include "xutil.h"

void xerror(char *msg, int line, char *file) {
	fprintf(stderr, "Error %d@%s: %s\n", line, file, msg);
	exit(EXIT_FAILURE);
}

uint32_t xfilesdir(char *folder) {                                              
	DIR *dir;                                                                   
	struct dirent *entry;                                                       
	unsigned int count = 0;                                                     

	if ((dir = opendir(folder)) == NULL) {                                      
		xerror(strerror(errno), __LINE__, __FILE__);                            
	}                                                                           

	while ((entry = readdir(dir)) != NULL) {                                    
		if (entry->d_type == DT_REG) { /* If the entry is a regular file */     
			count++;                                                            
		}                                                                       
	}                                                                           

	closedir(dir);                                                              

	return count;                                                               
}

void xmemset(void *p, size_t size) {
	if (p != NULL) {
		memset(p, '\0', size);
	}
}

void *xcalloc(size_t nmemb, size_t size) {
	void *p = calloc(nmemb, size);

	if (p == NULL) {
		xerror("Unable to c-allocate memory.", __LINE__, __FILE__);
	}

	return p;
}

void *xmalloc(size_t size) {
	void *p = malloc(size);

	if (p == NULL) {
		xerror("Unable to m-allocate memory.", __LINE__, __FILE__);
	}

	return p;
}
