/* insert.c - insert a substring into a string
 */

#include <string.h>


/* Insert the string "sub" into "str" at index "*n", taking care not to
 * overflow the buffer containing "str", which is assumed to be of "bufsize"
 * bytes starting at "str".
 *
 * The index, *n, is modified to point to the end of the inserted string.
 */
void mstrinsert(char *str, char *sub, int *n, long bufsize)
{
	int lstr, lsub;

	if ((!str) || (!sub) || (!n))
		return;
	lstr = strlen(str);
	lsub = strlen(sub);

	if ((lstr + lsub) > bufsize)
		return;			    /* won't fit in buffer */
	if (lsub < 1)
		return;			    /* nothing to do */
	if (*n > lstr)
		*n = lstr;

	memmove(str + (*n) + lsub, str + (*n), 1 + lstr - (*n));
	memcpy(str + (*n), sub, lsub);
	(*n) += lsub;
}

/* EOF */
