1 /***********************************************************
2 pm2tree.c -- tree for pmext2 decoding
3 ***********************************************************/
7 static unsigned char tree1left[32];
8 static unsigned char tree1right[32];
9 struct tree tree1 = { 0, tree1left, tree1right };
10 static unsigned char table1[32];
12 static unsigned char tree2left[8];
13 static unsigned char tree2right[8];
14 struct tree tree2 = { 0, tree2left, tree2right };
15 static unsigned char table2[8];
17 static unsigned char tree1bound;
18 static unsigned char mindepth;
25 tree1bound = getbits(5);
26 mindepth = getbits(3);
28 tree_setsingle(&tree1, tree1bound - 1);
31 for (i = 0; i < 32; i++)
34 for (i = 0; i < tree1bound; i++) {
36 table1[i] = (x == 0 ? 0 : x - 1 + mindepth);
38 tree_rebuild(&tree1, tree1bound, mindepth, 31, table1);
43 maketree2(int par_b) /* in use: 5 <= par_b <= 8 */
50 if (tree1bound == 29 && mindepth == 0)
53 for (i = 0; i < 8; i++)
55 for (i = 0; i < par_b; i++)
56 table2[i] = getbits(3);
60 for (i = 0; i < 8; i++) {
68 tree_setsingle(&tree2, index);
72 tree_rebuild(&tree2, 8, mindepth, 7, table2);
74 // Note: count == 0 is possible!
75 // Excluding that possibility was a bug in version 1.
80 tree_get(struct tree *t)
85 i = (getbits(1) == 0 ? t->leftarr[i] : t->rightarr[i]);
91 tree_setsingle(struct tree *t, unsigned char value)
93 t->root = 128 | value;
97 tree_rebuild(struct tree *t,
99 unsigned char mindepth,
100 unsigned char maxdepth,
101 unsigned char *table)
103 unsigned char parentarr[32], d;
104 int i, curr, empty, n;
108 unsigned int count[32];
111 memset(count, 0, sizeof(count));
112 for (i = 0; i < bound; i++) {
113 if (table[i] > maxdepth) {
120 for (i = 1; i <= maxdepth; i++) {
121 int max_leaves = (1<<i);
122 if (count[i] > max_leaves) {
126 total += 1.0/max_leaves * count[i];
129 /* check the Kraft's inequality */
135 /* initialize tree */
137 for (i = 0; i < bound; i++) {
144 for (i = 0; i < mindepth - 1; i++) {
145 t->leftarr[i] = i + 1;
146 parentarr[i + 1] = i;
151 for (d = mindepth; d <= maxdepth; d++) {
152 for (i = 0; i < bound; i++) {
156 if (t->leftarr[curr] == 0) {
157 t->leftarr[curr] = i | 128;
161 t->rightarr[curr] = i | 128;
163 while (t->rightarr[curr] != 0) {
164 if (curr == 0) { /* root? -> done */
167 curr = parentarr[curr];
171 t->rightarr[curr] = empty;
173 parentarr[empty] = curr;
180 t->leftarr[curr] = empty;
184 if (t->leftarr[curr] == 0)
185 t->leftarr[curr] = empty;
187 t->rightarr[curr] = empty;
189 parentarr[empty] = curr;