/* Search a string for another string and if the second string is found, replace
 * it with the replace string.
 *
 * $Log: srchrep.c,v $
 * Revision 1.2  1997/06/04 01:19:27  david
 * ANSI-fied the program.
 *
 */

static char *RcsId = "$Id: srchrep.c,v 1.2 1997/06/04 01:19:27 david Exp $";

/* lptr = Line to do the searching in */
/* maxsize = Max. size of lptr */
/* srchstr = String to search for */
/* repstr = String to replace srchstr */
void srchrep( char *lptr, int maxsize, char *srchstr, char *repstr )
{
int srchsize = strlen( srchstr );
int repsize = strlen( repstr );
int eosloc = strlen( lptr ); /* Position of End of String (NULL) */
register int loc = 0;
int temp;

while ( 1 )
   {
   while ( lptr[loc] != '\0' && lptr[loc] != srchstr[0] )
      loc++;

   if ( lptr[loc] == '\0' )
      break;

   if ( strncmp( &lptr[loc], srchstr, srchsize ) == 0 )
      {
      if ( srchsize == repsize )
         {
	 for ( temp = 0; temp < repsize; temp++ )
	    lptr[loc++] = repstr[temp];
	 continue;
	 }

      if ( repsize < srchsize )
	 {
	 /* Copy replace string */
	 for ( temp = 0; temp < repsize; temp++ )
	    lptr[loc++] = repstr[temp];

	 /* Fill in leftover characters */
	 for ( temp = loc; temp <= eosloc; temp++ )
	    lptr[loc++] = lptr[loc+srchsize-repsize];

	 eosloc -= srchsize - repsize;
	 continue;
	 }

      /* Expand line */
      if ( (eosloc + repsize - srchsize) > (maxsize - 1) )
	 eosloc = maxsize - 1;
       else
	 eosloc += repsize - srchsize;

      if ( loc + repsize > (maxsize - 1) )
	 repsize -= (loc + repsize) - (maxsize - 1);

      /* Open up room for new string */
      for ( temp = eosloc; temp > loc; temp-- )
	 lptr[temp] = lptr[temp-(repsize-srchsize)];

      /* Copy new string into old string + space */
      for ( temp = 0; temp < repsize; temp++ )
          lptr[loc+temp] = repstr[temp];

      loc += repsize; /* Skip past replacement */
      } /* End Found string */
    else /* String NOT FOUND */
     loc++; /* Bump pointer */
   } /* End while lptr */

lptr[eosloc] = '\0';
}
