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 };
14 static unsigned char tree2left[8];
15 static unsigned char tree2right[8];
16 static struct tree tree2 = { 0, tree2left, tree2right };
18 static void tree_setsingle(struct tree *t, unsigned char value);
19 static void tree_rebuild(struct tree *t, unsigned char bound,
20 unsigned char mindepth, unsigned char maxdepth,
21 unsigned char *table);
22 static void tree_setsingle(struct tree *t, unsigned char value);
28 unsigned char tree1bound;
29 unsigned char mindepth;
30 unsigned char table1[32];
32 tree1bound = getbits(5);
33 mindepth = getbits(3);
35 tree_setsingle(&tree1, tree1bound - 1);
38 for (i = 0; i < 32; i++)
41 for (i = 0; i < tree1bound; i++) {
43 table1[i] = (x == 0 ? 0 : x - 1 + mindepth);
45 tree_rebuild(&tree1, tree1bound, mindepth, 31, table1);
50 maketree2(int tree2bound) /* in use: 5 <= tree2bound <= 8 */
53 unsigned char table2[8];
55 for (i = 0; i < 8; i++)
57 for (i = 0; i < tree2bound; i++)
58 table2[i] = getbits(3);
62 for (i = 0; i < tree2bound; i++) {
70 tree_setsingle(&tree2, index);
73 tree_rebuild(&tree2, tree2bound, 1, 7, table2);
75 // Note: count == 0 is possible!
76 // Excluding that possibility was a bug in version 1.
81 tree_get(struct tree *t)
86 i = (getbits(1) == 0 ? t->leftarr[i] : t->rightarr[i]);
94 return tree_get(&tree1);
100 return tree_get(&tree2);
104 tree_setsingle(struct tree *t, unsigned char value)
106 t->root = 128 | value;
110 tree_rebuild(struct tree *t,
112 unsigned char mindepth,
113 unsigned char maxdepth,
114 unsigned char *table)
116 unsigned char parentarr[32], d;
117 int i, curr, empty, n;
121 unsigned int count[32];
124 memset(count, 0, sizeof(count));
125 for (i = 0; i < bound; i++) {
126 if (table[i] > maxdepth) {
133 for (i = mindepth; i <= maxdepth; i++) {
134 int max_leaves = (1<<i);
135 if (count[i] > max_leaves) {
139 total += 1.0/max_leaves * count[i];
142 /* check the Kraft's inequality */
148 /* initialize tree */
150 for (i = 0; i < bound; i++) {
157 for (i = 0; i < mindepth - 1; i++) {
158 t->leftarr[i] = i + 1;
159 parentarr[i + 1] = i;
164 for (d = mindepth; d <= maxdepth; d++) {
165 for (i = 0; i < bound; i++) {
169 if (t->leftarr[curr] == 0) {
170 t->leftarr[curr] = i | 128;
174 t->rightarr[curr] = i | 128;
176 while (t->rightarr[curr] != 0) {
177 if (curr == 0) { /* root? -> done */
180 curr = parentarr[curr];
184 t->rightarr[curr] = empty;
186 parentarr[empty] = curr;
193 t->leftarr[curr] = empty;
197 if (t->leftarr[curr] == 0)
198 t->leftarr[curr] = empty;
200 t->rightarr[curr] = empty;
202 parentarr[empty] = curr;