/* Stubby - Generate stubs for dynamic-link libraries.
 * Copyright 1999 Tom Rothamel
 *
 * Stubby is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version. It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * This program generates another computer program. I do not assert a      
 * copyright on the generated program that is the normal output of this    
 * program. This is _not_, however, an authorization for you to modify     
 * this program to cause it to output more of itself than necessary for    
 * its proper operation in order to circumvent my copyright.               
 */

/* This file contains string utility functions. */

#include <stdio.h>
#include <string.h>
#include <malloc.h>

/* Append one string to another. The destination can be NULL, in which
 * case it will be created. */
char *strappend(char *d, char *s) {
	int l;

	if (d) {
		l = strlen(d) + strlen(s) + 2;
		d = (char *) realloc(d, l);
		strncat(d, s, l); 		
	} else {
		l = strlen(s) + 2;
		d = (char *) malloc(l);
		strncpy(d, s, l);
	}
	return d;
}

/* STRing Append and Free */
char *straf(char *d, char *s) {
	char *n;

	n = strappend(d, s);
	free(s);

	return n;
}

/* This substitutes repl for pat in the string. It deallocates str
 * in favor of the new string. */
/* Warning! Bad things happend if repl containst pat! */
char *strsubst(char *str, char *pat, char *repl) {
	char *nstr;
	char *s;
	char *point;

	nstr = strdup(str);

	while (point = strstr(nstr, pat)) {
		s = nstr;

		*point = 0;
		point += strlen(pat);

		nstr = strdup(s);
		nstr = strappend(nstr, repl);
		nstr = strappend(nstr, point);

		free(s);
	}

	free(str);	
	return nstr;
}

