/****** UnRoff/UnRoff.c [1.0] ****************************************
*
* NAME
*    UnRoff.c
*
* DESCRITPION
*    Remove all the Backspace-character combinations that nroff &
*    it's derivatives place in their outout stream.
*
* SYNOPSIS
*    unroff infile [outfile]
*
* NOTES
*    $VER: UnRoff.c 1.0 (23-Nov-2001) by J.T. Steichen
**********************************************************************
*
*/

#include <stdio.h>

#include <exec/types.h>

#include <AmigaDOSErrs.h> // ERROR_ string #defines

static char v[] = "\0$VER: unroff 1.0 " __AMIGADATE__ " by J.T. Steichen";

static BOOL UseStdout = FALSE;
static char stripchar = 0x08; // The ASCII backspace character is 8.

int main( int argc, char **argv )
{
   FILE  *in = NULL, *out = NULL;
   char  ch1 = 0,     tmp = 0;

   if (argc == 2)
      {
      out       = stdout;
      UseStdout = TRUE;   // Guard against closing stdout handle.
      } 
   else if (argc > 3 || argc == 1)
      {     
      // What a bone-head user!
      fprintf( stderr, "\nUSAGE: %s infile [outfile]\n", argv[0] );

      if (argc > 3)
         return( ERROR_TOO_MANY_ARGS );
      else
         return( ERROR_REQUIRED_ARG_MISSING );
      }
/*
   else // From Workbench (argc == 0)
      {
      }
*/

   if ((in = fopen( argv[1], "rb" )) == NULL)
      {
      fprintf( stderr, "Couldn't open %s for reading!\n", argv[1] );

      return( IoErr() ); // Why, oh why, my beautiful Amiga??
      }

   if (UseStdout == FALSE)
      {
      if ((out = fopen( argv[2], "w" )) == NULL)
         {
         fclose( in );

         fprintf( stderr, "Couldn't open %s for writing!\n", argv[2] );

         return( IoErr() ); // Why, oh why, my beautiful Amiga??
         }
      }

   ch1 = fgetc( in );    // Read the first two characters
   tmp = ch1;
   ch1 = fgetc( in );

   if (tmp == stripchar)
      {
      tmp = ch1;         // Skip the first \b 
      ch1 = fgetc( in ); // Unless there's two \b's in a row (aarrgghh!!)
      }

   while (ch1 != EOF)
      {
      if (ch1 != stripchar)
         {
         fputc( tmp, out ); // safe to output trailing character

         tmp = ch1;
         ch1 = fgetc( in ); // reload & go again.

         if (ch1 == stripchar)
            {
            // discard both tmp & ch1 & reload them with the next two chars
            ch1 = fgetc( in );
            tmp = ch1;
            ch1 = fgetc( in );
            }
         }
      else
         {
         // discard both tmp & ch1 & reload them with the next two chars
         ch1 = fgetc( in );
         tmp = ch1;
         ch1 = fgetc( in );
         }
      }

   fclose( in );
  
   if (UseStdout == FALSE) // DO NOT close stdout, your shell will die!
      fclose( out );

   return( RETURN_OK );    // Weesa okey-dokey!
}
