#include<stdio.h>
#include<string.h>
#include <math.h>
 /*------------------------------------------------------------------------- */
int huff_table_vert(bits, huffval, ehufco, ehufsi, nval)
 unsigned char bits[];
 unsigned char huffval[];
 int nval;
 unsigned short ehufco[], ehufsi[];
 /* convert the Huffman table specified by the lists BITS and HUFFVAL
 in the interchange format into a useful Huffman table indexed by
 symbol in EHUFCO and EHUFSI where EHUFCO is the Huffman code table
 and EHUFSI is the length of each code */

 {
 unsigned char huffsize[256];
 unsigned short	huffcode[256], code, *pc;
 int	i, l, lastp, si, j, n;
 unsigned char *p, *pb;
 /* the bits array is 16 long, each entry is the number of codes
 with the length represented by the index, so bits[0] is the # of codes
 with size 1, bits[1] those of size 2, etc */
 /* some notes, the maximum Huffman code is 16 bits (hence the bits
 array of size populations is only 16 long); the codes are generated in
 a neat automatic way that only requires these size populations; it is
 important to generate the codes in the same way for encoding and
 decoding! The number of Huffman codes is assumed to be 256 or less
 (JPEG 12 bit will use 2 tables, 15 and 256 long), but the routine could
 be used for longer tables. */

 p = huffsize;
 pc = huffcode;
 code = 0;
 for (l = 0; l < 16; l++) {
   j = l + 1;	n = (int) bits[l];	/* n is the number of this length */
   while (n--)  {			/* the codes of a common length */
   /*printf("p-huffsize = %d, pc - huffcode = %d\n", p-huffsize,pc - huffcode);*/
	if ((p-huffsize) > 255) {
	printf("internal error in huff_table_vert\n"); return -1; }
	*p++ = (unsigned char) (j);	/* just increase by 1 wrt previous */
	*pc++ = code++;			   }
  	code <<= 1;			/* for new code size, left shift */
  }
  *p = 0;
  lastp = p - huffsize;
  if (lastp != nval) {
    printf("HUFF_TABLE_VERT, bits count (%d) != # of values (%d)\n",lastp,nval);
    return -1; }

 /* generate encoding tables, these use huffval, note that the codes
 are used in the order above, the huffval table tells us which value to
 use with each of these generated codes */
 
 n = nval;
 p = huffsize;
 pc = huffcode;
 pb = huffval;
 /*printf("n = %d\n", n);*/
 while (n--) {
   /*printf("*pb = %d\n", *pb);*/
   if (*pb > 255) {
	printf("internal error in huff_table_vert\n"); return -1; }
   ehufco[*pb] = *pc++;
   ehufsi[*pb] = (unsigned short) *p++;
   pb++;
 }
 return 1;
 }
 /*------------------------------------------------------------------------- */
