1 /***********************************************************
2 pm2tree.c -- tree for pmext2 decoding
3 ***********************************************************/
7 unsigned char root, *leftarr, *rightarr;
10 static unsigned char tree1left[32];
11 static unsigned char tree1right[32];
12 static struct tree tree1 = { 0, tree1left, tree1right };
13 static unsigned char tree1bound;
15 static unsigned char tree2left[8];
16 static unsigned char tree2right[8];
17 static struct tree tree2 = { 0, tree2left, tree2right };
19 static void tree_setsingle(struct tree *t, unsigned char value);
20 static void tree_rebuild(struct tree *t, unsigned char bound,
21 unsigned char mindepth, unsigned char maxdepth,
22 unsigned char *table);
23 static void tree_setsingle(struct tree *t, unsigned char value);
29 unsigned char mindepth;
30 unsigned char table1[32];
33 tree1bound = getbits(5);
34 mindepth = getbits(3);
36 tree_setsingle(&tree1, tree1bound - 1);
39 for (i = 0; i < 32; i++)
42 for (i = 0; i < tree1bound; i++) {
44 table1[i] = (x == 0 ? 0 : x - 1 + mindepth);
46 tree_rebuild(&tree1, tree1bound, mindepth, 31, table1);
51 maketree2(int tree2bound) /* in use: 5 <= tree2bound <= 8 */
54 unsigned char mindepth;
55 unsigned char table2[8];
60 if (tree1bound == 29 && mindepth == 0)
63 for (i = 0; i < 8; i++)
65 for (i = 0; i < tree2bound; i++)
66 table2[i] = getbits(3);
70 for (i = 0; i < tree2bound; i++) {
78 tree_setsingle(&tree2, index);
82 tree_rebuild(&tree2, tree2bound, mindepth, 7, table2);
84 // Note: count == 0 is possible!
85 // Excluding that possibility was a bug in version 1.
90 tree_get(struct tree *t)
95 i = (getbits(1) == 0 ? t->leftarr[i] : t->rightarr[i]);
103 return tree_get(&tree1);
109 return tree_get(&tree2);
113 tree_setsingle(struct tree *t, unsigned char value)
115 t->root = 128 | value;
119 tree_rebuild(struct tree *t,
121 unsigned char mindepth,
122 unsigned char maxdepth,
123 unsigned char *table)
125 unsigned char parentarr[32], d;
126 int i, curr, empty, n;
130 unsigned int count[32];
133 memset(count, 0, sizeof(count));
134 for (i = 0; i < bound; i++) {
135 if (table[i] > maxdepth) {
142 for (i = mindepth; i <= maxdepth; i++) {
143 int max_leaves = (1<<i);
144 if (count[i] > max_leaves) {
148 total += 1.0/max_leaves * count[i];
151 /* check the Kraft's inequality */
157 /* initialize tree */
159 for (i = 0; i < bound; i++) {
166 for (i = 0; i < mindepth - 1; i++) {
167 t->leftarr[i] = i + 1;
168 parentarr[i + 1] = i;
173 for (d = mindepth; d <= maxdepth; d++) {
174 for (i = 0; i < bound; i++) {
178 if (t->leftarr[curr] == 0) {
179 t->leftarr[curr] = i | 128;
183 t->rightarr[curr] = i | 128;
185 while (t->rightarr[curr] != 0) {
186 if (curr == 0) { /* root? -> done */
189 curr = parentarr[curr];
193 t->rightarr[curr] = empty;
195 parentarr[empty] = curr;
202 t->leftarr[curr] = empty;
206 if (t->leftarr[curr] == 0)
207 t->leftarr[curr] = empty;
209 t->rightarr[curr] = empty;
211 parentarr[empty] = curr;