/* I2A - wandelt IBM-Textfiles in AMIGA-Textfiles um.
 *  Das alte File wird ueberschrieben.
 *
 *  Aufruf:   I2A IBMfile
 *
 *  BY Juergen Schlie  -- GUZZI 01/1991
 */

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

#define tblength 16
#define EXT ".GUZZI"

int  table[] = {
          142,196,  153,214,  154,220,  132,228,
          148,246,  129,252,  225,223,  158,223 };
          /* links IBM,rechts AMIGA */
          /* Ä */   /* Ö */   /* Ü */   /* ä */
          /* ö */   /* ü */   /* ß */   /* ß ATARI == 158 */

void usage ( filename )
char *filename;
{
   printf("USAGE : %s IBMfile \n",filename);
   printf("Converts IBM 'Umlaute' and Linefeeds to AMIGA -- GUZZI 01/1991\n");
   exit(1);
}

main ( argc , argv )
int argc;
char *argv[];
{
   char infile[80], outfile[80];
   FILE *in_fp, *out_fp;
   int j, c;

   if ( argc != 2 )
       usage ( argv[0] );

   sprintf ( infile  , argv[1] );
   sprintf ( outfile , argv[1] );
   strcat  ( outfile , EXT     );

   if ( access ( outfile , 0 ) == 0 )   /* outfile already exists */
   {
       fprintf ( stderr , " %s -- Output file already exists ! \n" , argv[0] );
       exit(1);
   }

   if ( ! (in_fp  = fopen ( infile  , "rb" )) )
       usage ( argv[0] );

   if ( ! (out_fp = fopen ( outfile , "wb" )) )
   {
       if ( in_fp ) fclose ( in_fp );
       usage ( argv[0] );
   }

   while (( c = fgetc( in_fp ) ) != EOF )
   {
       if ( c > 128 )
           for(j=0;j < tblength; j+=2)      /* Tabelle absuchen  */
               if( c == table[j] )          /* nach Umlauten     */
                   c = table[j+1];

       if ( c != 0x0D )                     /* ^M auslassen      */
           fputc ( c , out_fp );            /* Zeichen ausgeben  */
   }

   if ( in_fp  ) fclose ( in_fp );
   if ( out_fp ) fclose ( out_fp );

   if ( remove ( infile ) < 0 )
   {
       fprintf ( stderr , " %s -- FATAL error ! \n" , argv[0] );
       exit(1);
   }
   if ( rename ( outfile , infile ) < 0 )
   {
       fprintf ( stderr , " %s -- FATAL error ! \n" , argv[0] );
       exit(1);
   }

   fprintf ( stderr , " %s -- Converted file %s to AMIGA ! \n" ,
                                                     argv[0] , infile );
}
