#include <zlib.h>
#include "libopgp.h"

#define NTPKTP 9
#define NTPSIZ (1<<NTPKTP)

#define OBSIZ 512               /* (8383+NTPSIZ*2) */
#define IBSIZ 16
int PGP_zlvl = 6;
int PGP_zip(FILE * inf, FILE * outf, int v2f)
{
  z_stream pgpz;
  int readgot, isav;
  unsigned char ibuf[IBSIZ], obuf[OBSIZ];

  memset(&pgpz, 0, sizeof(pgpz));
  fputc(v2f ? 0xa3 : 0xc8, outf);
  obuf[0] = v2f < 2 ? 1 : 2;
  pgpz.next_out = obuf + 1, pgpz.avail_out = OBSIZ - 1;
  deflateInit2(&pgpz, PGP_zlvl, Z_DEFLATED,
               !v2f ? -13 : (v2f < 2 ? -13 : 13), 5, 0);
  readgot = IBSIZ;
  while (!feof(inf) && readgot == IBSIZ) {
    if (0 >= (readgot = fread(ibuf, 1, IBSIZ, inf)))
      break;
    pgpz.next_in = ibuf;
    pgpz.avail_in = readgot;
    while (pgpz.avail_in || readgot != IBSIZ) {
      isav = deflate(&pgpz, readgot == IBSIZ ? 0 : Z_FINISH);
      if (pgpz.avail_out == NTPSIZ) {
        if (!v2f)
          fputc(0xe0 + NTPKTP, outf);
        fwrite(obuf, 1, NTPSIZ, outf);
        pgpz.avail_out = NTPSIZ;
        pgpz.next_out = obuf;
      }
      if (isav != Z_OK)
        break;
    }
  }
  if (!v2f) {
    if (OBSIZ - pgpz.avail_out > 192) {
      fputc(0xc0 | ((OBSIZ - pgpz.avail_out - 192) >> 8), outf);
      fputc(OBSIZ - pgpz.avail_out - 192, outf);
    } else
      fputc(OBSIZ - pgpz.avail_out, outf);
  }
  fwrite(obuf, 1, OBSIZ - pgpz.avail_out, outf);
  deflateEnd(&pgpz);
  return 0;
}
