/* Quick file editor Search and replace functions */
/* Programmer: A.Le Couteur Bisson  October 88 */
/* Compiles under Lattice C 4.0 (I haven't tried any other compilers) */

#include <stdio.h>
#include <dos.h>

/* I don't know why Lattice force me to do this! */
#define dread  _dread
#define dopen  _dopen
#define dclose _dclose

int quiet  = 0;
int backup = 0;
int show   = 0;
long fhandle,nc,fsize;
char *buffer;

extern void search(char **,long,long);
extern long filesize(char *);
extern void dobackup(char *);
extern int query(char *,char *,int);

void main(argc,argv)
int argc;
char *argv[];
{
  char *fname;

  if(argc<=2)
  {
    puts("Usage: change [-qbs] <file> (<old_string> <new_string>) ...\n");
    puts("-b backup -q quiet -s show\n");
    exit(0);
  }
/*
 * Check for options - as thouroughly as possible
 */
  while(**++argv=='-' && --argc>0)
  {
    char *c;
    for(c=argv[0]+1; *c!='\0'; c++)
    { 
      switch(*c)
      {
        case 'q': quiet=1;
                  break;
        case 'b': backup=1;
                  break;
        case 's': show=1;
	          break;
        default : printf("Illegal option -%c\n",*c);
                  exit(1);
      }
    }
  }
  if(show) backup=quiet=0; /* remove incompatible options */
  if(!show && (argc & 1)) /* Must be an even number of strings if not showing */
  {
    puts("Replace string missing\n");
    exit(1);
  }
/*
 * Allocate a buffer for the file
 */
  fname=*argv;
  fsize=filesize(fname);
  buffer=(char *)malloc(fsize);
  if(!buffer)
  {
    puts("Not enough memory for file\n");
    exit(2);
  }
  if((fhandle=dopen(fname,MODE_OLDFILE))==-1)
  {
    printf("Cannot open file : %s\n",fname);
    exit(1);
  }
/*
 * Read the file into the buffer
 */
  if(dread(fhandle,buffer,fsize) != fsize)
  {
    puts("Cannot read all of the input file");
    dclose(fhandle);
    exit(2);
  }
  dclose(fhandle);
  if(backup) dobackup(fname);
/*
 * It's now open season on the input file
 * (you did use the -b option didn't you.....)
 */
  if((fhandle=dopen(fname,MODE_NEWFILE))==-1)
  {
    puts("Cannot open output file");
    exit(2);
  }
/*
 * Pass search() pointer to the string pointers and string pair count
 * Note that 1st two args skipped ( "change" and <file> )
 */
  search(argv+1,argc-2,fhandle);
  dclose(fhandle);
  printf("%d change(s) made\n",nc);
}

