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

static char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                  "0123456789+/";
#ifdef TESTINGmime
int hex_encode(FILE *fin, FILE *fout);
main()
{
	FILE *fin,*fout;
	fin = fopen("in.txt","rb");
	fout = fopen("out.txt","w");
	hex_encode(fin,fout);
	return 0;
}
#endif

int base64_encode(FILE *fin, FILE *fout){
   int  index, shift, save_shift;
   int help_flag = 0, replace_flag = 0, perm_replace_flag = 0, quit = 0;
   int cycle_flag = 0;
   unsigned char blivit;
   unsigned long accum, value;
   char buf[80];
   int firsttime = 1;
   int skipflag = 0;
   int printmsg = 1;


   {
      shift = 0;
      accum = 0;
      index = 0;
      while ( ( !feof( fin ) ) || (shift != 0) )
      {
         if ( ( !feof( fin ) ) && ( quit == 0 ) )
         {
            blivit = fgetc( fin );

            if ( feof( fin ) )
            {
               quit = 1;
               save_shift = shift;
               blivit = 0;
            }
         }
         else
         {
            quit = 1;
            save_shift = shift;
            blivit = 0;
         }

         if ( (quit == 0) || (shift != 0) )
         {
            value = (unsigned long)blivit;
            accum <<= 8;
            shift += 8;
            accum |= value;
         } /* ENDIF */

         while ( shift >= 6 )
         {
            shift -= 6;
            value = (accum >> shift) & 0x3Fl;
            blivit = alphabet[value];

            buf[index++] = blivit;
            if ( index >= 60 )
            {
               buf[index] = '\0';
               fprintf( fout, "%s\n", buf );
               index = 0;
            }

            if ( quit != 0 )
            {
               shift = 0;
            }
         }
      }

      if      ( save_shift == 2 )
      {
         buf[index++] = '=';
         if ( index >= 60 )
         {
            buf[index] = '\0';
            fprintf( fout, "%s\n", buf );
            index = 0;
         }

         buf[index++] = '=';
         if ( index >= 60 )
         {
            buf[index] = '\0';
            fprintf( fout, "%s\n", buf );
            index = 0;
         }
      }
      else if ( save_shift == 4 )
      {
         buf[index++] = '=';
         if ( index >= 60 )
         {
            buf[index] = '\0';
            fprintf( fout, "%s\n", buf );
            index = 0;
         }
      }

      if ( index != 0 )
      {
         buf[index] = '\0';
         fprintf( fout, "%s\n", buf );
      }
   }
   fclose(fin); fclose(fout);
   return 1;
}
