/*
**      $VER: StripAOL.c 1.00 (3.1.98)
**
**      Strips proprietary AOL email JPEG header from file
**
**      (C) Copyright 1998 Andreas R. Kleinert
**      Freeware. All Rights Reserved.
*/

#define __USE_SYSBASE

#include <exec/types.h>
#include <exec/memory.h>

#include <proto/exec.h>

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


#ifndef N
#define N (NULL)
#endif /* N */


char ver_text [] = "\0$VER: StripAOL 1.00 (3.1.98)";


/* *************************************************** */
/* *                                                 * */
/* * Additional Base Declarations                    * */
/* *                                                 * */
/* *************************************************** */

extern struct ExecBase *SysBase;


/* *************************************************** */
/* *                                                 * */
/* * MAIN                                            * */
/* *                                                 * */
/* *************************************************** */

void __regargs __chkabort(void) { }
void __regargs _CXBRK(void)     { }


void main(long argc, char **argv)
{
 ULONG error = 0;

 if(argc == 3)
  {
   FILE *in, *out;

   in = fopen(argv[1], "rb");
   if(in)
    {
     ULONG i, found = FALSE;
     char *inbuf;
     UBYTE chk[256];

     inbuf = malloc(16384);
     if(inbuf) setbuf(in, inbuf);

     fread(&chk[0], 256, 1, in);

     for(i=0; i<248; i++)
      {
       if(!strncmp(&chk[i], "JPEG8BIM", 8))
        {
         found = TRUE;
         break;
        }
      }

     if(found)
      {
       found = FALSE;

       for( ; i<252; i++)
        {
         if(chk[i] == 0xFF)
           if(chk[i+1] == 0xD8)
             if(chk[i+2] == 0xFF)
               if(chk[i+3] == 0xE0) { found = TRUE; break; }
        }

       if(found)
        {
         out = fopen(argv[2], "wb");
         if(out)
          {
           int c;
           char *outbuf;

           outbuf = malloc(16384);
           if(outbuf) setbuf(out, outbuf);

           fwrite(&chk[i], 256-i, 1, out);

           while( (c = fgetc(in)) != EOF) fputc(c, out);

           fclose(out);

           if(outbuf) free(outbuf);

          }else
          {
           printf("\n ERROR: Can't open outfile\n");
           error = 20;
          }
        }else
        {
         printf("\n ERROR: Unsupported kind of AOL JPEG\n");
         error = 20;
        }
      }else
      {
       printf("\n ERROR: Is not an AOL JPEG\n");
       error = 20;
      }

     fclose(in);

     if(inbuf) free(inbuf);

    }else
    {
     printf("\n ERROR: Can't open infile\n");
     error = 20;
    }

  }else
  {
   printf("\n Strips proprietary AOL email JPEG header.");
   printf("\n Written 1998 by Andreas R. Kleinert <Andreas_Kleinert@t-online.de>");
   printf("\n Usage: INFILE OUTFILE\n\n");
  }

 exit(error);
}
