/*
  Copyright (C) 1989      Fung F. Lee

  Amiga porting 1999 by Fabrizio "Lanch^DarkAge" Bartoloni
  gb2hz: convert GB file into a HZ file.

  This program is free for general distribution.  

  This source is slightly modified to compile under Amiga.

*/

#include <stdio.h>

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

int CR2LF=false;	/* flag for converting ASCII <CR> to <LF> */
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 'n': CR2LF = true; 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);
return (0);
}

warning()
{
  fprintf(stderr, "usage: %s [-n] [-t[maximum-line-length]] < foo > foo.hz\n",
	  progname);
  exit(1);
}

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

      /* c1 is ASCII */
      else
	{
	  if (GBmode) {fprintf(fout, "~}"); len += 2;}
	  /* assert(len<=MAXLEN-1) */
	  if (termStyle && (len>MAXLEN-2 || len>MAXLEN-3 && c1=='~'))
	    {
	      fprintf(fout, "~\n");
	      len = 0;
	    }
	  GBmode = false;
	  if (CR2LF && c1=='\r') c1 = '\n';
	  fputc(c1, fout);
	  len++;
	  if (c1=='\n') len=0;
	  else if (c1== '~') {fputc('~', fout); len++;}
	}
    }
  if (GBmode) fprintf(fout, "~}");
}



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

