#include "libopgp.h"

/* output buffer size - this is space efficient */
#define OBSIZ 512

void PGP_xctb(FILE * inf, FILE * outf)
{
  u32_t neof, ll, k, mark, tot;
  char dbuf[OBSIZ];

  while (!feof(inf)) {
    mark = 0, tot = 0;
    ll = fgetc(inf);
    if (ll == -1)
      return;
    if (ll == 0xa8) {
      k = fgetc(inf);
      while (k--)
        ll = fgetc(inf);
      ll = fgetc(inf);
    }
    if (ll != 0xc8) {
      ll = ((ll & 0x0f) << 2) | 0x82;
      fputc(ll, outf);          /* this is for the CTB */
      mark = ftell(outf);
      for (k = 0; k < 4; k++)
        fputc(0, outf);
    } else
      fputc(0xa3, outf);        /* compression uses internal EOT */

    ll = 0;
    neof = 1;
    while (!feof(inf) && neof) {
      if (!ll && neof)
        ll = PGP_nxpkt(&neof, inf);
      while (ll) {
        if (0 >= (k = fread(dbuf, 1, ll > OBSIZ ? OBSIZ : ll, inf)))
          break;
        fwrite(dbuf, 1, k, outf);
        ll -= k;
        tot += k;
      }
    }
    ll = ftell(outf);
    if (!mark || fseek(outf, mark, SEEK_SET))
      continue;
    fputc(tot >> 24, outf), fputc(tot >> 16, outf);
    fputc(tot >> 8, outf), fputc(tot, outf);
    fseek(outf, ll, SEEK_SET);
  }
}
