/* b64.c - convert MIME base64 to clear file format */
/* author Neil Franklin, last modification 1995.12.10 */

/* this was originally written to decode an base64 Mail sent to me
   in the days when I had an NeXTcube with an none-MIME capable mailer */

/* Note: there is a bug somewhere in this,
   after about 1k the 8th bit of the output is randomly broken.
   I did not fix it, as the original base64 was only 7bit,
   and I later on Linux got mimencode to do this job */

/* to use this program do as following:
   - compile it with  cc -o b64 b64.c
   - display MIME base64 Mail in any mailer
   - cut%paste the  QmlsbCBHYXRlcyBpbiB  stuff to an file
   - run as  ./b64 < infile > outfile
   - view the clear file with less or IGF viewer */

#include <stdio.h>

void main(void) {
  char asc2bin[0x80]; int i;
  for (i = 0   ; i <= 0x7F; i++) asc2bin[i]    =        -1;
  for (i = 0x41; i <= 0x5A; i++) asc2bin[i]    = i-0x41;
  for (i = 0x61; i <= 0x7A; i++) asc2bin[i]    = i-0x61+26;
  for (i = 0x30; i <= 0x39; i++) asc2bin[i]    = i-0x30+52;
                                 asc2bin[0x2E] =        62;
                                 asc2bin[0x2F] =        63;
  for (;;) {
    char cryptline[100], *crypt = cryptline;
    char plainline[100], *plain = plainline;
    fgets(cryptline, 100, stdin);
    if (feof(stdin)) break;
    while (*crypt >= 0x20) {
      char b1 = asc2bin[*crypt++];
      char b2 = asc2bin[*crypt++];
      char b3 = asc2bin[*crypt++];
      char b4 = asc2bin[*crypt++];
                    *plain++ = b1<<2|b2>>4;
      if (b3 != -1) *plain++ = b2<<4|b3>>2;
      if (b4 != -1) *plain++ = b3<<6|b4; }
    fwrite(plainline, 1, plain-plainline, stdout); }
  exit(0); }
