#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define FILENAME_LEN 100
#define STRLEN 100

void exit_help(char *prog, char *errorstr)
{
  puts(errorstr);
  printf("Usage: %s filename\n", prog);
  printf("   where filename is of type .bbl generated with bibtex style html-alpha.bst.\n");
  printf("This program will convert filename.bbl to filename.html\n");
  exit(0);
}

int main(int argc, char *argv[])
{
  int test,nest=0,caps=0;
  char endsym[5];
  FILE *infp, *outfp;
  char infilename[FILENAME_LEN];
  char outfilename[FILENAME_LEN];
  char error[STRLEN];
  char c,c_prev;

  if (argc<2) {
    exit_help(argv[0], "Error: no file to convert\n"); 
  }
  if (argc>2) {
    exit_help(argv[0], "Error: too many filenames\n"); 
  }
  strcpy(infilename,argv[1]);
  strcat(infilename,".bbl");
  if ((infp=fopen(infilename,"r"))==NULL) {
    sprintf(error,"Error: cannot read file %s\n", infilename);
    exit_help(argv[0], error);
  }
  strcpy(outfilename,argv[1]);
  strcat(outfilename,".html");
  if ((outfp=fopen(outfilename,"w"))==NULL) {
    sprintf(error,"Error: cannot write to file %s\n", outfilename);
    exit_help(argv[0], error);
  }
  c = fgetc(infp);
  while (c != EOF) {
    /*
      grave = back slash.  Example: &agrave; --> a\
      aigu = forward slash.  Example: &eacute; --> e/
      circonflexe = caret.  Example: &ecirc; --> e^
      cedille = comma.  Example &ccedil; --> c,
      trema = double quote.  Example  &ouml; --> o"
      */
    if (c_prev==92) { /* backslash */
      c_prev = c; 
      c = fgetc(infp);
      if (c=='{') {c = fgetc(infp); test=1;}
      switch(c_prev) {
      case 39: /* ' */ fprintf(outfp,"&%cacute;",c); break;
      case 96: /* ` */ fprintf(outfp,"&%cgrave;",c); break;
      case 34: /* " */ fprintf(outfp,"&%cuml;",c); break;
      case 'c':
	fprintf (outfp,"&%ccedil;",c);
	putchar(c);
	break;
      case '^': fprintf(outfp,"&%ccirc;",c); break;
      case 't': /* \tt */ fprintf(outfp,"<tt>"); strcpy(endsym,"</tt>"); break;
      case 'i': /* \it */ fprintf(outfp,"<i>"); strcpy(endsym,"</i>"); break;
      case 'e': /* \em */ fprintf(outfp,"<i>"); strcpy(endsym,"</i>"); break;
      case 'r': /* \rm */ break;
      case 's': /* \sc, \sf, \sl */ 
	switch (c) {
	case 'c': caps=1; strcpy(endsym,""); break;
	case 'f': break;
	case 'l': fprintf(outfp,"<i>"); strcpy(endsym,"</i>"); break;
	}
      }
      if (test) { fgetc(infp); test=0;}

    } else if ((c=='~') && (c_prev != '/')) {
      fputc(' ',outfp);
    } else if (c==92) {
    } else if (c=='{') {
      nest++;
    } else if (c=='}') {
      fputs(endsym,outfp);strcpy(endsym,"");caps=0;
      nest--;
    } else if (c=='%') {
      c = fgetc(infp);
    } else {
      if (caps) {
	fputc(toupper(c),outfp);
      } else {
	fputc(c,outfp);
      }
    }
    c_prev = c;
    c = fgetc(infp);
  }

  fclose(outfp);
  fclose(infp);
  return 0;
}
