#include <malloc.h>
#include "libpgp5.h"

/*------------------------------------------------------------------------*/
/* should be > 8128 */
#define RBSIZ 10000

int cnvdec5(FILE * inf, FILE * outf, void *cfbdat)
{
  unsigned char dbuf[RBSIZ];
  unsigned int i, j, ll, neof;

  ll = fgetc(inf);
  neof = 0;
  if (ll != 0xc9 && (ll & 0xfc) != 0xa4) {
    free(cfbdat);
    return -3;
  }
  if (ll == 0xc9) {
    if ((ll = fgetc(inf)) >= 0xc0) {
      if (ll >= 0xe0)
        if (ll == 0xff)
          for (i = 0, ll = 0; i < 4; i++)
            ll = (ll << 8) + fgetc(inf);
        else
          neof = 1, ll = 1 << (ll & 31);  /* noteof */
      else
        ll = ((ll & 31) << 8) + 192 + fgetc(inf);
    }
  } else {
    j = 1 << (ll & 3);
    for (i = 0, ll = 0; i < j; i++)
      ll = (ll << 8) + fgetc(inf);
  }
  if (ll < 10)
    return -5;
  ll -= 10;
  j = fread(dbuf, 1, 10, inf);  /*X WONT WORK IF FRAGMENTED */
  if (j != 10)
    return -5;
  memcpy(&dbuf[20], &dbuf[2], 8);
  docfb(dbuf, 10, cfbdat);
  if (dbuf[6] != dbuf[8] || dbuf[7] != dbuf[9]) {
    free(cfbdat);
    return -7;
  }
  cfbreset(&dbuf[20], cfbdat);  /* PGP special restart */
  while (ll) {                  /* depacket and decrypt */
    i = ll > RBSIZ ? RBSIZ : ll;
    j = fread(dbuf, 1, i, inf);
    docfb(dbuf, j, cfbdat);
    i = fwrite(dbuf, 1, j, outf);
    ll -= j;
    if (!ll && neof--) {
      if ((ll = fgetc(inf)) >= 0xc0) {
        if (ll >= 0xe0)
          neof = 1, ll = 1 << (ll & 31);  /* noteof */
        else
          ll = ((ll & 31) << 8) + 192 + fgetc(inf);
      }
    }
  }
  free(cfbdat);
  return 0;
}
