/***********************************************************************
*
*  projet   : DilibPro
*  commande : StrReplace
*  fichier  : StrReplace.c
*  Auteur   : Jacques DUCLOY
*  Date     : Octobre 93
*
*************************************************************************/

#include <string.h>
#include <stdio.h>
char *malloc();
void perror();

static char *buffer;
static char *stringSearch;
static char *stringRep;
static int  sizeBuffer;
static char* currentPosition;
static char* middlePosition;
static char *endBuffer;

int nextBuffer()
{
  static int EofHasBeenFounded=0;
  static int EofHasBeenTreated=0;
  char *insertPoint;
  int c; /* char c; */

  if (EofHasBeenFounded) 
    {
     if (EofHasBeenTreated)return (0);
     EofHasBeenTreated=1;     
     strcpy(buffer, currentPosition);
     return (1);
   }
  if (currentPosition)
    {
      strcpy(buffer, currentPosition);
      insertPoint=buffer+strlen(buffer);
    }
  else
    {
      insertPoint=buffer;
    }
  do
    {
      if((c=getchar())==EOF)
	{
	  *insertPoint='\0';
	  EofHasBeenFounded=1;
	  return (1);
	}
      else *insertPoint=c;
    }
  while(insertPoint++ < endBuffer);
  *insertPoint='\0';
  return (1);
}

/***************************** main ***********************************/
void usage()
{
  perror ("usage: StrReplace [-s string] [-t string] [-l size]\n");
  exit(1);
}

    int getopt();
    extern char *optarg;


void main(argc,argv)
     int argc;
     char **argv;
{
  int cod_arg;
  int sizeCompare;

  stringSearch=NULL;
  stringRep="";
  
  while ((cod_arg = getopt(argc,argv,"s:l:t:"))!=EOF)
    {
      switch(cod_arg) 
	{
	case 's':
	  stringSearch=optarg;
	  break;
	case 'l':
	  break;
	case 't':
	  stringRep=optarg;
	  break;
	default:
	  usage();
	}
    }

  sizeBuffer=1024+2 *strlen(stringSearch);
  buffer=(char *)malloc(sizeBuffer+1);
  endBuffer=buffer+sizeBuffer;
  middlePosition=buffer+sizeBuffer/2+1;
  currentPosition=NULL;
  sizeCompare=strlen(stringSearch);

  while (nextBuffer())
    {
      currentPosition=buffer;
      do
	{
	if (*currentPosition==0) exit(0);
	  if (*currentPosition==*stringSearch)
	    {
	      if(strncmp(currentPosition+1, stringSearch+1, sizeCompare-1)==0)
		{
		  printf(stringRep);
		  currentPosition+=sizeCompare;
		}
	      else putchar(*currentPosition++);
	    }
	  else  putchar(*currentPosition++);
	}
      while(currentPosition<middlePosition);
    }
   exit (0);
}





