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

extern char mtab[65];
extern unsigned long crctab[256];

/*-------------------------*/
/* called by dearmor, with NULL ofd to get crc */
unsigned long unmime(FILE * ifd, FILE * ofd)
{
  char c[4];
  int i, q;
  long t;
  char *s1;
  unsigned long ccrc = 0xB704CE;

  i = 4;
  while (i == 4 && !feof(ifd)) {
    for (i = 0; i < 4; i++) {
      q = 64;
      while (!feof(ifd)) {
        t = fgetc(ifd);
        while (!ofd && t == '=')
          t = fgetc(ifd);
        if (t == '-' || t == -1) {
          q = 64;
          break;
        }
        if ((s1 = strchr(mtab, t)) == NULL)
          continue;
        q = s1 - mtab;
        break;
      }
      if (q == 64)
        break;
      c[i] = q;
    }
    t = c[0], t <<= 6, t |= c[1], t <<= 6, t |= c[2], t <<= 6, t |= c[3];
    if (!ofd)
      return t;
    if (i)
      fputc(t >> 16, ofd),
        ccrc = ccrc << 8 ^ crctab[0xff & ((ccrc >> 16) ^ t >> 16)];
    if (i >= 3)
      fputc(t >> 8, ofd),
        ccrc = ccrc << 8 ^ crctab[0xff & ((ccrc >> 16) ^ t >> 8)];
    if (i == 4)
      fputc(t, ofd),
        ccrc = ccrc << 8 ^ crctab[0xff & ((ccrc >> 16) ^ t)];
  }
  return ccrc & 0xffffff;
}

/*-------------------------*/
/* dearmor - should also return cert type and headers... */
int dearmor(FILE * ifd, FILE * ofd)
{
  unsigned char dbuf[4096];
  unsigned long calccrc, savecrc;

  while (!feof(ifd)) {
    fgets(dbuf, 4095, ifd);
    /* find pgp armored data cert */
    if (strncmp(dbuf, "-----BEGIN PGP ", 15))
      continue;                 /* not start */
    if (!strncmp(dbuf, "-----BEGIN PGP SIGNED MESSAGE-----", 34))
      continue;                 /* not message text */
    /* headers - NOTE THIS WILL NOT WORK IF THERE ARE \r\n endings */
    while (dbuf[0] != '\n')
      fgets(dbuf, 4095, ifd);
    calccrc = unmime(ifd, ofd);
    savecrc = unmime(ifd, NULL);
    if (calccrc != savecrc)
      return -1;
  }
  return 0;
}
