#include "libopgp.h"

#define MAXLEN 2048
void *PGP_gtpkt(FILE * inf, u8_t ctb, u32_t * gaz)
{
  u32_t ll, gazouta, neof = 0, i, k;
  u8_t *bufptr, *bp;

  gazouta = 0;
  if (ctb < 0xc0) {
    i = 1 << (ctb & 3);         /* length of length */
    for (k = 0, ll = 0; k < i; k++)
      ll = (ll << 8) + fgetc(inf);
  } else
    ll = PGP_nxpkt(&neof, inf);
  if (ll > MAXLEN || !ll)
    return NULL;
  bufptr = malloc(neof ? MAXLEN + 1 : ll + 1);  /* +1 to add final null */

  bp = bufptr;
  for (;;) {
    gazouta += ll;
    if (gazouta > MAXLEN) {
      if (0 >= (i = fread(bp, 1, MAXLEN - gazouta, inf)))
        exit(-2);
      gazouta += i - ll;
      ll = 0, neof = 0;
    }
    while (ll) {
      if (0 >= (i = fread(bp, 1, ll, inf)))
        exit(-2);
      ll -= i, bp += i;
    }
    if (!neof) {
      bufptr[gazouta] = 0;
      if (gaz)
        *gaz = gazouta;
      return bufptr;
    }
    ll = PGP_nxpkt(&neof, inf);
  }
}
