/*
  Copyright (C) 1989      Fung F. Lee
  Copyright (C) 1994      Stephen G. Simpson

  gb2hzp: convert a GB file into a HZ+ file.

  This program is free for general distribution.  

*/

#include <stdio.h>

#define true 1
#define false 0
#define notAscii(c)	((c)&0x80)

int termStyle = false;	/* enforce terminal emulation style if true */
int MAXLEN = 77;	/* default maximum line length in the above style */
int MINLEN = 7;		/* minimum line length in the above style */
char *progname;

main(argc, argv)
     int argc;
     char *argv[];
{
  int i, len;

  progname = argv[0];
  for (i=1; i<argc; i++)
    {
      if (argv[i][0]!='-') warning();
      switch (argv[i][1])
	{
	case 'f':
	    setbuf(stdout, NULL);
	    break;
	case 't': termStyle = true;
	  if ((argv[i][2]!='\0') && (sscanf(&argv[i][2], "%d", &len) != 1))
	    warning();
	  if (len >= MINLEN) MAXLEN = len;
	  break;
	default:  warning(); break;
	}
    }
  filter(stdin, stdout);
}

warning()
{
  fprintf(stderr, "usage: %s [-f] [-t[maximum-line-length]] < foo.gb > foo.hzp\n",
	  progname);
  fprintf(stderr, "       -f means do not buffer output\n");
  exit(1);
}

filter(fin, fout)
     FILE *fin, *fout;
{
  int c1, c2, c3, c4, hi;
  int GBmode = false;
  int len = 0;
  int tilde = 0;
  int ascii = 1;
  
  while ((c1=fgetc(fin)) != EOF)
    {
      if (notAscii(c1))
        {
	  if (termStyle)
	    {
	      if (GBmode && len>MAXLEN-5)
		{
		  fprintf(fout, "~}~\n");
		  GBmode = false;
		  len = 0;
		  ascii = 1;
		}
	      else if (!GBmode && len>MAXLEN-7)
		{
		  fprintf(fout, "~\n");
		  GBmode = false;
		  len = 0;
		  ascii = 1;
		}
	    }
	  if (!GBmode) /* switch to GB mode */
	    {
	      fprintf(fout, "~{");
	      len += 2;
	      tilde = 0;
	      ascii = 0;
	    }
	  GBmode = true;
	  c2 = fgetc(fin);
	  gb2hzp(c1, c2, &c3, &c4);
	  fputc(c3, fout);
	  fputc(c4, fout);
	  len += 2;
	}
      /* c1 is ASCII */
      else
	{
	  if (GBmode)
	      {
		  fprintf(fout, "~}");
		  len += 2;
		  GBmode = false;
		  ascii = 1;
	      }
	  if (termStyle && (len>MAXLEN-2 || len>MAXLEN-3 && c1=='~'))
	    {
	      fprintf(fout, "~\n");
	      len = 0;
	      ascii = 1;
	    }
	  if (tilde==1)
	      {
		  if (c1 == '{' || c1 == '<' || c1 == '>')
		      ascii = 0;
		  else if (c1 == '}' || c1 == '\n' || c1 == '~')
		      ascii = 1;
		  else if (ascii == 1)
		      {
			  fputc('~', fout);
			  len++;
		      }
	      }
	  fputc(c1, fout);
	  len++;
	  if (c1=='\n') len=0;
	  if (c1== '~' && tilde == 0)
	      tilde = 1;
	  else tilde = 0;
	}
    }
  if (GBmode) fprintf(fout, "~}");
}


gb2hzp(hi, lo, hi1, lo1)
     int hi, lo, *hi1, *lo1;
{
  *hi1 = hi - 0x80;
  *lo1 = lo - 0x80;
}

