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

unsigned char mtab[66] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=-";

extern unsigned long crctab[256];

/* these are globals so programs may change them */
char defcert[64] = "MESSAGE";
char aaheader[64] = "Version: OpenPrivacy 0.9";
/*-------------------------*/
/* armor - should allow specifying the cert type and header */
int armor(FILE * ifd, FILE * ofd, char *certype, char *headtxt)
{
  unsigned char in[3], out[4];
  int i, j, q;
  unsigned long ccrc = 0xB704CE;
  char *cert, *hdr;

  cert = certype ? certype : defcert;
  hdr = headtxt ? headtxt : aaheader;
  fprintf(ofd, "-----BEGIN PGP %s-----\n%s\n\n", cert, hdr);
  q = 0;
  for (;;) {
    memset(in, 0, 3);
    i = fread(in, 1, 3, ifd);
    out[0] = mtab[in[0] >> 2];
    out[1] = mtab[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)];
    out[2] = mtab[((in[1] << 2) & 0x3c) | ((in[2] >> 6) & 0x03)];
    out[3] = mtab[in[2] & 0x3f];
    for (j = 0; j < i; j++)
      ccrc = ccrc << 8 ^ crctab[0xff & ((ccrc >> 16) ^ in[j])];
    if (i < 3)
      break;
    fwrite(out, 1, 4, ofd);
    q += 4;
    if (q == 64) {
      fputc('\n', ofd);
      q = 0;
    }
  }
  if (i) {
    out[3] = '=';
    if (i == 1)
      out[2] = '=';
    fwrite(out, 1, 4, ofd);
    q = 4;
  }
  if (q)
    fputc('\n', ofd);
  fputc('=', ofd);
  in[0] = ccrc >> 16, in[1] = ccrc >> 8, in[2] = ccrc;
  out[0] = mtab[in[0] >> 2];
  out[1] = mtab[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)];
  out[2] = mtab[((in[1] << 2) & 0x3c) | ((in[2] >> 6) & 0x03)];
  out[3] = mtab[in[2] & 0x3f];
  fwrite(out, 1, 4, ofd);
  fputc('\n', ofd);
  fprintf(ofd, "-----END PGP %s-----\n", cert);
  return 0;
}
