char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                  "0123456789+/";




int encode64( char *src, int srclen, char *dest, int destlen )
{
   int shift, save_shift;
   unsigned char blivit;
   unsigned long accum, value;
   int srcpos = 0, destpos = 0;

   int quit = 0;

      shift = 0;
      accum = 0;
      while ( srcpos < srclen || (shift != 0) )
      {
         if ( ( srcpos < srclen ) && ( quit == 0 ) )
         {
            blivit = *src++;

            if ( ++srcpos >= srclen )
            {
               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];

            if (destpos++ < destlen) {
            	*dest++ = blivit;
            }

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

      if      ( save_shift == 2 )
      {
         if (destpos++ < destlen) {
          	*dest++ = '=';
         }
         if (destpos++ < destlen) {
          	*dest++ = '=';
         }

      }
      else if ( save_shift == 4 )
      {
         if (destpos++ < destlen) {
          	*dest++ = '=';
         }
      }

     if (destpos < destlen) {
       	*dest = '\0';
      }
      return destpos < destlen ? 0 : destpos + 1;
}
