
#include "lib.h"

char *
str_replace (char *str, char const *search, char const *replace)
{
  char
   *cp, *tail, *tailcopy;
  int
    searchlen = strlen (search), index = 0;

  for (index = 0; str[index]; index++)
    {
      cp = str + index;
      if (!strncmp (cp, search, searchlen))
	{
	  if (replace && *replace)
	    {
	      tail = cp + searchlen;

	      if (*tail)
		{
		  tailcopy = xstrdup (tail);
		  *cp = '\0';
		  str = str_concat (str, replace);
		  str = str_concat (str, tailcopy);
		  free (tailcopy);
		}
	      else
		{
		  *cp = '\0';
		  str = str_concat (str, replace);
		}
	      index += strlen (replace) - 1;
	    }
	  else
	    strcpy (cp, cp + searchlen);
	}
    }

  return (str);
}
