/* reads a database 'refs' with a list of string tokens
and a replacement string, separated by a <tab> character.
Then for each argument, replaces all occurrances of the token
string with the replacement string. Similar to sed but capable
of doing much bigger lists */

#include <stdio.h>
#include <string.h>
#define LEN 256

FILE *f,*o;
char inp[LEN], key[LEN], rep[LEN], command[LEN];
struct entry {char *key, *rep; struct entry *next;} *table;
char c,c1,c2;
int firstline;
char *outrep, *p;
void mkentry(key,rep) char *key,*rep; {
     struct entry *newentry;
     newentry = (struct entry*) malloc(sizeof (struct entry));
     newentry->key = strdup(key);
     newentry->rep = strdup(rep);
     newentry->next = table;
     table = newentry;
}

char *findrep(key) char *key; {
     struct entry *next;
     int missing;
     next = table;
     while ( (missing=strcmp(next->key,key)) && (next = next->next));
     if (missing) return NULL; else return next->rep;
}

main(argc,argv) int argc; char **argv; {
  char *s1,*s2;
  f = fopen("refs","r");
  while (fgets(inp,LEN,f) != NULL) {
	/* printf("%s\n",inp); */
	s1= strtok(inp,"\t"); s2= strtok(NULL,"\n");
        mkentry(s1, s2);
  }
  fclose (f);

  /* get each file argument */
  argc--;
  while (argc--) {
     argv++;
     f = fopen(*argv,"r");
     o = fopen("tmp","w");
     p = key; firstline = 1;
     while ((c= fgetc(f)) != EOF) {
          if (isalpha(c) || isdigit(c))  *p++ = c;
          else {
             *p = '\0';
             if (firstline && strcmp(key,"From") == 0) { 
             /* this is e-mail, remove headers */
               do fgets(inp,LEN,f); while (strlen(inp) > 1);
             }
             firstline = 0;
             /* omit if no keyword or preceding "> - indicating
                 possible hyperlink already */
             if (*key) {
                if (c2 != '"' || c1 !='>') {
                   outrep= findrep(key);
                   if (outrep) fputs(outrep,o); else fputs(key,o);
                } else fputs(key,o);
                fputc(c,o);
             }
             else fputc(c,o);
             p = key;
             c2= c1; c1= c;
          }
     }
     fclose(f); fclose(o);
     sprintf(command,"mv tmp %s",*argv);
     system(command);
  }
}
