Listing 3 functions that compress a data record using Huffman encoding.

#include "hufftree.h"

/*
------------------------ compress ----------------------------
/*

void compress(int inlen, char *bufin, int *outlen, char
*bufout)
{
  int c, i;
  
  bufout[(*outlen)++] = inlen;
  for (i=0; i<inlen; i++)
  { c = bufin[i];
    encode((c & 255), 0, outlen, bufout);
  }
  emit(-1, outlen, bufout);

}


/*
------------------------- encode -----------------------------
*/

void encode(short h, short child, int *outlen, char *bufout)
{
  if (ht[h].parent != 0)
    encode(ht[h].parent, h, outlen, bufout);
  if (child)
  { if (child == ht[h].right)
      emit(0, outlen, bufout);
    else if (child == ht[h].left)
      emit(1, outlen, bufout);
  }
}


static char byt;
static int cnt;

/*
------------------------- emit -------------------------------
*/

void emit(int bit, int *outlen, char *bufout)
{
  if (bit == -1)
  { while (cnt != 8)
    { byt = byt << 1;
      cnt++;
    }
    bufout[(*outlen)++] = byt;
    byt = 0;
    cnt = 0;
    return;
  }
  if (cnt == 8)
  { bufout[(*outlen)++] = byt;
    byt = 0;
    cnt = 0;
  }
  byt = (byt << 1) | bit;
  cnt++;
}

/* End of File */