/* uuclean.c ... remove extraneous stuff from captured
   uuencoded files 12 Sep 1995 */

#include <stdio.h>
#define INCHARS 128
#define MAX 6

main(int argc,char *argv[])

{
   FILE *infile;
   FILE *outfile;
   char instring[INCHARS];
   char oldstring[INCHARS];
   char teststr[MAX];
   char testend[MAX];
   char oneback[INCHARS];
   char twoback[INCHARS];
   char threeback[INCHARS];
   char current[INCHARS];
   static char beginstr[] =  "begin";
   static char endstr[] = "end";
   static char mstring[] = "M";
   int i;
   int start = 1;
   int end = 1;
   
   if (argc != 3)
   {
      printf ("\n UUCLEAN by rdavis@nyx.cs.du.edu (Robert Davis), version 0.2");
      printf ("\n Usage: %s INPUT OUTPUT \n INPUT and OUTPUT are filenames\n"
      ,argv[0]);
      exit(1);
   }  

   if (( infile = fopen(argv[1],"r")) == NULL)
   {
      printf ("\n Cannot open %s\n",argv[1]);
      exit(1);
   }
   
   if (( outfile = fopen(argv[2],"w")) == NULL)
   {
      printf ("\n Unable to open output file %s\n",argv[2]);
      exit(2);
   }
   printf ("\n Working ... \n");
   
   while (fgets (instring,INCHARS,infile) != NULL)
   {   
      strcpy (threeback,twoback);
      strcpy (twoback,oneback);
      strcpy (oneback,current);
      strcpy (current,instring);
   
      /* first, find   begin  */
      for (i=0;i<5;i++)
         teststr[i] = instring[i];
      teststr[i] = 0x00;
      
      for (i=0;i<3;i++)
         testend[i] = instring[i];
      testend[i] = 0x00;
               
      start = (strcmp(beginstr,teststr));
      end = (strcmp(endstr,testend));
           
      if (start == 0)
        fputs (instring,outfile);  /* fputs the first line of the uuencoded file */
        
      if (end == 0)
        { fputs (twoback,outfile); /* this might be a problem with some files */
          fputs (oneback,outfile);
          fputs (instring,outfile);
          break; } /* fputs the last lines of the uuencoded file */
  
      /* compare then copy the new string to the old string */
      
      if ((strcmp (oldstring,instring) != 0) &&
          (strcmp (twoback,instring) != 0) &&
          (strcmp (threeback,instring) != 0))
        {         
         if (*instring == *mstring) /* if first char in line is M */
            { fputs (instring,outfile);
              strcpy (oldstring,instring); }            
        }
   }
   fclose (outfile);
   fclose (infile);
   printf ("\n Done.\n");
}
