#include "libopgp.h"

#define RBSIZ 512
/* won't work for multiples with different lengths, but to mark where... */
#define BSZ 8
int PGP_cdec(FILE * inf, FILE * outf, void *cfbdat[], int cfbcnt)
{
  u8_t dbuf[RBSIZ];
  u32_t k, j, ll, neof, cc = 32767, ct;

  ll = fgetc(inf);
  neof = 0;
  if (ll != 0xc9 && (ll & 0xfc) != 0xa4) {
    free(cfbdat);
    return -3;
  }
  if (ll == 0xc9)
    ll = PGP_nxpkt(&neof, inf);
  else {
    j = 1 << (ll & 3);
    for (k = 0, ll = 0; k < j; k++)
      ll = (ll << 8) + fgetc(inf);
  }
  if (PGP_gtblk(dbuf, 10, &ll, &neof, inf))
    return -5;
  memcpy(&dbuf[10], dbuf, 10);
  for (ct = 0; ct < cfbcnt; ct++) {  /* test each key context */
    PGP_cblk(dbuf, 10, cfbdat[ct]);
    if (dbuf[6] == dbuf[8] && dbuf[7] == dbuf[9]) {
      if (cc != 32767) {
        fprintf(stderr, "Warning: Duplicate good key found\n");
        free(cfbdat[ct]);
      } else
        cc = ct;
    } else
      free(cfbdat[ct]);
    memcpy(dbuf, &dbuf[10], 10);
  }
  if (cc == 32767)
    return -7;
  PGP_cres(&dbuf[20 - BSZ], cfbdat[cc]);  /* PGP reset */
  while (ll) {                  /* depacket and decrypt */
    k = ll > RBSIZ ? RBSIZ : ll;
    if (0 >= (j = fread(dbuf, 1, k, inf)))
      exit(-2);
    PGP_cblk(dbuf, j, cfbdat[cc]);
    k = fwrite(dbuf, 1, j, outf);
    ll -= j;
    if (!ll && neof)
      ll = PGP_nxpkt(&neof, inf);
  }
  free(cfbdat[cc]);
  return 0;
}
