#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <gtk/gtk.h>
#include "main.h"


/* -------------- some small, useful string funtions ------------- */

/* ANSI C doesn't have a strdup */
char *my_strdup(char *string) {
	int i ;
	char *res = NULL ;

	if(!string) return NULL ;

	i = strlen(string) ;
	res = malloc(i + 1) ;
	if(!res) return NULL ;

	strcpy(res, string) ;
	return res ;
}


/* exchange all occurencies of 'from' in 'string' by 'to' */
char *my_strsubst(char *string, char *from, char *to) {
	char *tmp, *t, *p, *res ;

	res = NULL ;
	tmp = my_strdup(string) ;
	t = tmp ;

	if(!string || !from || !to) return NULL ;

	while( (p = strstr(t, from)) ) {
		*p = '\0' ;
		if(!res) {
			res = malloc(strlen(t) + strlen(to) + 1) ;
			*res = '\0' ;
		} else res = realloc(res, strlen(res) + strlen(t) + strlen(to) + 1) ;
		strcat(res, t) ;
		strcat(res, to) ;
		t = p + strlen(from) ;
	}

	if(!res) {
		res = malloc(strlen(t) + 1) ;
		strcpy(res, t) ;
	} else {
		res = realloc(res, strlen(res) + strlen(t) + 1) ;
		strcat(res, t) ;
	}

	free(tmp) ;
	return res ;
}


/* Standard warning message */
void say(int level, char *message, ...) {
	va_list vl ;
	FILE *output=stderr ;

	if(!debug && level >= 0) return ;

	va_start(vl, message) ;

	fprintf(output, "arka:- ") ;
	vfprintf(output, message, vl) ;
	fprintf(output, "\n") ;

}


/* issue a message and exit */
void die(char *message, ...) {
	va_list vl ;

	va_start(vl, message) ;

	say(-1, message, vl) ;
	exit(EXIT_FAILURE) ;

}
