/* Convert Unixstyle Charactersequences to Amiga Sequences              */
/* Just another 1/2 hour hack ! No comments here, no comments there :-) */
/* Compile with Lattice C : lc -L convert.c                             */
/* Compile with GCC : gcc -O2 -o convert convert.c -lc -lamiga          */
/* Ulrich Diedrichsen 15.9.92 (Free off rights,support & warranty)      */

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define BOLDON "\2331m"
#define UNDERLINEON "\2334m"
#define MODEOFF "\2330m"
#define FILEBUFFERSIZE 128
#define TRUE 1
#define FALSE 0

int main(int argc,char **argv)
{
 unsigned char buffer[FILEBUFFERSIZE];
 unsigned long newbytes,i,pos,bytes,start;
 char B_ON,U_ON;
 
 if ((strcmp(argv[1],"?")==0)||(strcmp(argv[1],"-h")==0)||(strcmp(argv[1],"help")==0)) {
  printf("%s\n%sUSAGE :%s %s%s%s\n",MODEOFF,BOLDON,MODEOFF,UNDERLINEON,argv[0],MODEOFF);
  printf(" Converts reads from stdin unixstyle bold & underline sequence to\n");
  printf(" Amiga Esc sequences and prints result to stdout.\n");
  printf(" E.g.: call convert <man.0 >man.man\n\n");
 } else {
  B_ON=FALSE;  
  U_ON=FALSE;
   newbytes=FILEBUFFERSIZE;
   start=0;
   while ((bytes=fread(&buffer[start],1,newbytes,stdin))>0) {
    pos=0;
    bytes+=start;
    while ((pos+2)<bytes) {
     if (buffer[pos+1]==8) {
      if (buffer[pos]=='_') {
       if (U_ON) putchar(buffer[pos+2]);
       else {
        U_ON=TRUE;
        printf("%s%c",UNDERLINEON,buffer[pos+2]);
       }
      } else {
       if (B_ON) putchar(buffer[pos]);
       else {
        B_ON=TRUE;
        printf("%s%c",BOLDON,buffer[pos]);
       }
      }
      pos+=3;
     } else {
      if (U_ON || B_ON) {
       printf("%s",MODEOFF);
       U_ON=B_ON=FALSE;
      }
      putchar(buffer[pos++]);
     }
    }
    if (bytes<newbytes) for (i=pos;i<bytes;i++) putchar(buffer[i]);
    else {
     for (i=pos;i<bytes;i++) buffer[i-pos]=buffer[i];
     start=bytes-pos;
     newbytes=FILEBUFFERSIZE-start;
    }
   }
   if (U_ON||B_ON) printf("%s\n",MODEOFF);
  }
 return(0);
}
