#include "libpgp5.h"

/*------------------------------------------------------------------------*/
/* should be > 8192+192 */
#define RBSIZ 10000

int cnvdec5(FILE * inf, FILE * outf, unsigned char *keybuf, unsigned int cy)
{
  unsigned char dbuf[RBSIZ], *bp;
  int i, j, k, neof;

  memset(dbuf, 0, 32);
  cfbinit(keybuf, dbuf, cy);
  bp = dbuf;
  if (fgetc(inf) != 0xc9)
    return -3;                  /* should be c9 */

  neof = 0;                     /* length chunks to length */
  k = fgetc(inf);
  if (k >= 0xc0) {
    if (k >= 0xe0)
      neof = 1, k = 1 << (k & 31);  /* noteof */
    else {
      k = ((k & 31) << 8) + 192;
      k += fgetc(inf);
    }
  }
  j = fread(dbuf, 1, 10, inf);
  memcpy(&dbuf[20], &dbuf[2], 8);
  docfb(dbuf, 10, 0);
  if (dbuf[6] != dbuf[8] || dbuf[7] != dbuf[9])
    return -7;
  k -= 10;
  cfbreset(&dbuf[20]);          /* PGP special restart */
  while (k) {                   /* depacket and decrypt */
    i = k > RBSIZ ? RBSIZ : k;
    j = fread(dbuf, 1, i, inf);
    docfb(dbuf, j, 0);
    j = fwrite(dbuf, 1, i, outf);
    k -= i;
    if (!k && neof) {
      neof = 0;                 /* same as above */
      k = fgetc(inf);
      if (k >= 0xc0) {
        if (k >= 0xe0)
          neof = 1, k = 1 << (k & 31);  /* noteof */
        else {
          k = ((k & 31) << 8) + 192;
          k += fgetc(inf);
        }
      }
    }
  }
  return 0;
}
