wow-mpq 0.6.2

High-performance parser for World of Warcraft MPQ archives with parallel processing support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! Huffman compression implementation for MPQ archives (StormLib-compatible)
//!
//! This is a complete rewrite to match StormLib's linked list approach.
//! Based on the algorithm from Ladislav Zezula's StormLib.

use crate::{Error, Result};

// Huffman tree constants
const HUFF_ITEM_COUNT: usize = 0x203; // Number of items in the item pool
const LINK_ITEM_COUNT: usize = 0x80; // Maximum number of quick-link items
const HUFF_DECOMPRESS_ERROR: u32 = 0x1FF;

// All weight tables from StormLib - these define the initial character frequencies
const BYTE_TO_WEIGHT_00: [u8; 258] = [
    0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_01: [u8; 258] = [
    0x54, 0x16, 0x16, 0x0D, 0x0C, 0x08, 0x06, 0x05, 0x06, 0x05, 0x06, 0x03, 0x04, 0x04, 0x03, 0x05,
    0x0E, 0x0B, 0x14, 0x13, 0x13, 0x09, 0x0B, 0x06, 0x05, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02,
    0x0D, 0x07, 0x09, 0x06, 0x06, 0x04, 0x03, 0x02, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02,
    0x09, 0x06, 0x04, 0x04, 0x04, 0x04, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x04,
    0x08, 0x03, 0x04, 0x07, 0x09, 0x05, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02,
    0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02,
    0x06, 0x0A, 0x08, 0x08, 0x06, 0x07, 0x04, 0x03, 0x04, 0x04, 0x02, 0x02, 0x04, 0x02, 0x03, 0x03,
    0x04, 0x03, 0x07, 0x07, 0x09, 0x06, 0x04, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02,
    0x0A, 0x02, 0x02, 0x03, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x03, 0x05, 0x02, 0x03,
    0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01,
    0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x04, 0x04, 0x04, 0x07, 0x09, 0x08, 0x0C, 0x02,
    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x03,
    0x04, 0x01, 0x02, 0x04, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
    0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x02, 0x02, 0x02, 0x06, 0x4B,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_02: [u8; 258] = [
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x27, 0x00, 0x00, 0x23, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xFF, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x01, 0x01, 0x06, 0x0E, 0x10, 0x04,
    0x06, 0x08, 0x05, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02, 0x01, 0x01,
    0x01, 0x04, 0x02, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x04, 0x01, 0x01, 0x02, 0x03, 0x03, 0x02,
    0x03, 0x01, 0x03, 0x06, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x01, 0x01,
    0x01, 0x29, 0x07, 0x16, 0x12, 0x40, 0x0A, 0x0A, 0x11, 0x25, 0x01, 0x03, 0x17, 0x10, 0x26, 0x2A,
    0x10, 0x01, 0x23, 0x23, 0x2F, 0x10, 0x06, 0x07, 0x02, 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_03: [u8; 258] = [
    0xFF, 0x0B, 0x07, 0x05, 0x0B, 0x02, 0x02, 0x02, 0x06, 0x02, 0x02, 0x01, 0x04, 0x02, 0x01, 0x03,
    0x09, 0x01, 0x01, 0x01, 0x03, 0x04, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
    0x05, 0x01, 0x01, 0x01, 0x0D, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x02, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
    0x0A, 0x04, 0x02, 0x01, 0x06, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x01, 0x01, 0x01,
    0x05, 0x02, 0x03, 0x04, 0x03, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x03, 0x03,
    0x01, 0x03, 0x01, 0x01, 0x02, 0x05, 0x01, 0x01, 0x04, 0x03, 0x05, 0x01, 0x03, 0x01, 0x03, 0x03,
    0x02, 0x01, 0x04, 0x03, 0x0A, 0x06, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x02, 0x02, 0x01, 0x0A, 0x02, 0x05, 0x01, 0x01, 0x02, 0x07, 0x02, 0x17, 0x01, 0x05, 0x01, 0x01,
    0x0E, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x06, 0x02, 0x01, 0x04, 0x05, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01,
    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01,
    0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x11,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_04: [u8; 258] = [
    0xFF, 0xFB, 0x98, 0x9A, 0x84, 0x85, 0x63, 0x64, 0x3E, 0x3E, 0x22, 0x22, 0x13, 0x13, 0x18, 0x17,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_05: [u8; 258] = [
    0xFF, 0xF1, 0x9D, 0x9E, 0x9A, 0x9B, 0x9A, 0x97, 0x93, 0x93, 0x8C, 0x8E, 0x86, 0x88, 0x80, 0x82,
    0x7C, 0x7C, 0x72, 0x73, 0x69, 0x6B, 0x5F, 0x60, 0x55, 0x56, 0x4A, 0x4B, 0x40, 0x41, 0x37, 0x37,
    0x2F, 0x2F, 0x27, 0x27, 0x21, 0x21, 0x1B, 0x1C, 0x17, 0x17, 0x13, 0x13, 0x10, 0x10, 0x0D, 0x0D,
    0x0B, 0x0B, 0x09, 0x09, 0x08, 0x08, 0x07, 0x07, 0x06, 0x05, 0x05, 0x04, 0x04, 0x04, 0x19, 0x18,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_06: [u8; 258] = [
    0xC3, 0xCB, 0xF5, 0x41, 0xFF, 0x7B, 0xF7, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xBF, 0xCC, 0xF2, 0x40, 0xFD, 0x7C, 0xF7, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x7A, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_07: [u8; 258] = [
    0xC3, 0xD9, 0xEF, 0x3D, 0xF9, 0x7C, 0xE9, 0x1E, 0xFD, 0xAB, 0xF1, 0x2C, 0xFC, 0x5B, 0xFE, 0x17,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xBD, 0xD9, 0xEC, 0x3D, 0xF5, 0x7D, 0xE8, 0x1D, 0xFB, 0xAE, 0xF0, 0x2C, 0xFB, 0x5C, 0xFF, 0x18,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x70, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

const BYTE_TO_WEIGHT_08: [u8; 258] = [
    0xBA, 0xC5, 0xDA, 0x33, 0xE3, 0x6D, 0xD8, 0x18, 0xE5, 0x94, 0xDA, 0x23, 0xDF, 0x4A, 0xD1, 0x10,
    0xEE, 0xAF, 0xE4, 0x2C, 0xEA, 0x5A, 0xDE, 0x15, 0xF4, 0x87, 0xE9, 0x21, 0xF6, 0x43, 0xFC, 0x12,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0xB0, 0xC7, 0xD8, 0x33, 0xE3, 0x6B, 0xD6, 0x18, 0xE7, 0x95, 0xD8, 0x23, 0xDB, 0x49, 0xD0, 0x11,
    0xE9, 0xB2, 0xE2, 0x2B, 0xE8, 0x5C, 0xDD, 0x15, 0xF1, 0x87, 0xE7, 0x20, 0xF7, 0x44, 0xFF, 0x13,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x5F, 0x9E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00,
];

// Weight tables lookup - all 9 tables that StormLib supports
const WEIGHT_TABLES: [&[u8; 258]; 9] = [
    &BYTE_TO_WEIGHT_00,
    &BYTE_TO_WEIGHT_01,
    &BYTE_TO_WEIGHT_02,
    &BYTE_TO_WEIGHT_03,
    &BYTE_TO_WEIGHT_04,
    &BYTE_TO_WEIGHT_05,
    &BYTE_TO_WEIGHT_06,
    &BYTE_TO_WEIGHT_07,
    &BYTE_TO_WEIGHT_08,
];

/// Bit stream reader for Huffman decompression
struct BitReader<'a> {
    data: &'a [u8],
    position: usize,
    bit_buffer: u32,
    bit_count: u32,
}

impl<'a> BitReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self {
            data,
            position: 0,
            bit_buffer: 0,
            bit_count: 0,
        }
    }

    fn get_bit(&mut self) -> Result<u32> {
        if self.bit_count == 0 {
            if self.position >= self.data.len() {
                return Err(Error::compression("Unexpected end of Huffman data"));
            }
            self.bit_buffer = self.data[self.position] as u32;
            self.position += 1;
            self.bit_count = 8;
        }

        let bit = self.bit_buffer & 1;
        self.bit_buffer >>= 1;
        self.bit_count -= 1;
        Ok(bit)
    }

    fn get_8_bits(&mut self) -> Result<u32> {
        if self.position >= self.data.len() {
            return Err(Error::compression("Unexpected end of Huffman data"));
        }
        let byte = self.data[self.position] as u32;
        self.position += 1;
        Ok(byte)
    }

    fn peek_7_bits(&mut self) -> Result<u32> {
        // Ensure we have enough bits in the buffer
        while self.bit_count < 7 {
            if self.position >= self.data.len() {
                return Err(Error::compression("Unexpected end of Huffman data"));
            }
            self.bit_buffer |= (self.data[self.position] as u32) << self.bit_count;
            self.position += 1;
            self.bit_count += 8;
        }

        Ok(self.bit_buffer & 0x7F) // Get lower 7 bits
    }

    fn skip_bits(&mut self, count: u32) {
        if count <= self.bit_count {
            self.bit_buffer >>= count;
            self.bit_count -= count;
        } else {
            let remaining = count - self.bit_count;
            self.bit_buffer = 0;
            self.bit_count = 0;
            self.position += (remaining / 8) as usize;
            // Handle remaining bits if any
            if !remaining.is_multiple_of(8) && self.peek_7_bits().is_ok() {
                self.skip_bits(remaining % 8);
            }
        }
    }
}

/// Huffman tree node based on StormLib's THTreeItem
#[derive(Debug, Clone)]
struct HuffmanItem {
    // Linked list pointers
    next: Option<usize>, // Pointer to lower-weight tree item
    prev: Option<usize>, // Pointer to higher-weight item

    // Tree structure
    decompressed_value: u32, // 08 - Decompressed byte value (also index in the array)
    weight: u32,             // 0C - Weight
    parent: Option<usize>,   // 10 - Pointer to parent item (NULL if none)
    child_lo: Option<usize>, // 14 - Pointer to the child with lower-weight child ("left child")

                             // In StormLib, the higher-weight child is accessed via pChildLo->pPrev
}

impl HuffmanItem {
    fn new(value: u32, weight: u32) -> Self {
        Self {
            next: None,
            prev: None,
            decompressed_value: value,
            weight,
            parent: None,
            child_lo: None,
        }
    }
}

/// Quick link structure for optimized decompression
#[derive(Debug, Clone)]
struct QuickLink {
    valid_value: u32,
    valid_bits: u32,
    decompressed_value: u32,
    item_index: Option<usize>,
}

impl QuickLink {
    fn new() -> Self {
        Self {
            valid_value: 0,
            valid_bits: 0,
            decompressed_value: 0,
            item_index: None,
        }
    }
}

/// Huffman tree based on StormLib
struct HuffmanTree {
    items: Vec<HuffmanItem>,
    items_by_byte: [Option<usize>; 0x102],
    quick_links: [QuickLink; LINK_ITEM_COUNT],
    first: Option<usize>, // Pointer to the highest weight item
    last: Option<usize>,  // Pointer to the lowest weight item
    min_valid_value: u32,
}

// Virtual list head marker
const LIST_HEAD: Option<usize> = None;

impl HuffmanTree {
    fn new() -> Self {
        Self {
            items: Vec::with_capacity(HUFF_ITEM_COUNT),
            items_by_byte: [None; 0x102],
            quick_links: std::array::from_fn(|_| QuickLink::new()),
            first: LIST_HEAD,
            last: LIST_HEAD,
            min_valid_value: 1,
        }
    }

    // Link two items in the linked list
    fn link_two_items(&mut self, item1_idx: usize, item2_idx: usize) {
        // pItem2->pNext = pItem1->pNext;
        self.items[item2_idx].next = self.items[item1_idx].next;

        // pItem2->pPrev = pItem1->pNext->pPrev;
        if let Some(next_idx) = self.items[item1_idx].next {
            self.items[item2_idx].prev = self.items[next_idx].prev;
            // pItem1->pNext->pPrev = pItem2;
            self.items[next_idx].prev = Some(item2_idx);
        } else {
            // item1 was the last item
            self.items[item2_idx].prev = Some(item1_idx);
        }

        // pItem1->pNext = pItem2;
        self.items[item1_idx].next = Some(item2_idx);
    }

    // Insert item after a given position
    fn insert_after(&mut self, new_item_idx: usize, after_idx: Option<usize>) {
        if let Some(idx) = after_idx {
            self.link_two_items(idx, new_item_idx);
        } else {
            // Insert at the beginning of the list
            self.items[new_item_idx].prev = None;
            self.items[new_item_idx].next = self.first;

            if let Some(first_idx) = self.first {
                self.items[first_idx].prev = Some(new_item_idx);
            }

            self.first = Some(new_item_idx);

            if self.last.is_none() {
                self.last = Some(new_item_idx);
            }
        }
    }

    // Insert item before a given position
    fn insert_before(&mut self, new_item_idx: usize, before_idx: Option<usize>) {
        if let Some(idx) = before_idx {
            // Get the previous item
            let prev_idx = self.items[idx].prev;

            self.items[new_item_idx].next = Some(idx);
            self.items[new_item_idx].prev = prev_idx;
            self.items[idx].prev = Some(new_item_idx);

            if let Some(prev) = prev_idx {
                self.items[prev].next = Some(new_item_idx);
            } else {
                // This was the first item
                self.first = Some(new_item_idx);
            }
        } else {
            // Insert at the end of the list
            self.items[new_item_idx].next = None;
            self.items[new_item_idx].prev = self.last;

            if let Some(last_idx) = self.last {
                self.items[last_idx].next = Some(new_item_idx);
            }

            self.last = Some(new_item_idx);

            if self.first.is_none() {
                self.first = Some(new_item_idx);
            }
        }
    }

    // Create a new item and add it to the list
    fn create_new_item(
        &mut self,
        decompressed_value: u32,
        weight: u32,
        insert_after: bool,
    ) -> usize {
        let new_idx = self.items.len();
        self.items
            .push(HuffmanItem::new(decompressed_value, weight));

        // For the initial list, just append to the end
        // The fixup function will move it to the correct position
        if self.first.is_none() {
            self.first = Some(new_idx);
            self.last = Some(new_idx);
        } else if insert_after {
            self.insert_after(new_idx, self.last);
        } else {
            self.insert_before(new_idx, self.first);
        }

        new_idx
    }

    // Find item with weight >= given weight
    fn find_higher_or_equal_item(&self, start_idx: Option<usize>, weight: u32) -> Option<usize> {
        let mut current = start_idx;

        while let Some(idx) = current {
            if self.items[idx].weight >= weight {
                return Some(idx);
            }
            current = self.items[idx].prev;
        }

        None
    }

    // Fix item position by weight (insertion sort)
    fn fixup_item_pos_by_weight(&mut self, item_idx: usize, mut max_weight: u32) -> u32 {
        let item_weight = self.items[item_idx].weight;

        // If this item's weight is less than max_weight, we need to move it
        if item_weight < max_weight {
            // Find the item with weight >= this item's weight, searching backwards from last
            if let Some(higher_idx) = self.find_higher_or_equal_item(self.last, item_weight) {
                // Remove item from its current position
                self.remove_item_from_list(item_idx);

                // Insert after the found item (LinkTwoItems behavior)
                self.insert_after(item_idx, Some(higher_idx));
            }
        } else {
            // This is the new maximum weight
            max_weight = item_weight;
        }

        max_weight
    }

    // Remove item from linked list (but keep in items array)
    fn remove_item_from_list(&mut self, item_idx: usize) {
        let prev = self.items[item_idx].prev;
        let next = self.items[item_idx].next;

        if let Some(prev_idx) = prev {
            self.items[prev_idx].next = next;
        } else {
            // This was the first item
            self.first = next;
        }

        if let Some(next_idx) = next {
            self.items[next_idx].prev = prev;
        } else {
            // This was the last item
            self.last = prev;
        }

        self.items[item_idx].prev = None;
        self.items[item_idx].next = None;
    }

    fn build_tree(&mut self, compression_type: u32) -> Result<()> {
        // Clear all items
        self.items.clear();
        self.items_by_byte = [None; 0x102];
        self.first = LIST_HEAD;
        self.last = LIST_HEAD;

        // Ensure compression type is valid
        let comp_type = (compression_type & 0x0F) as usize;
        if comp_type >= WEIGHT_TABLES.len() {
            return Err(Error::compression("Invalid Huffman compression type"));
        }

        let weight_table = WEIGHT_TABLES[comp_type];

        // Build the linear list of entries that is sorted by byte weight
        // First pass: create all items
        for (i, &weight) in weight_table.iter().enumerate().take(0x100) {
            if weight != 0 {
                let item_idx = self.create_new_item(i as u32, weight as u32, true);
                self.items_by_byte[i] = Some(item_idx);
            }
        }

        // Insert termination entries
        let end_idx = self.create_new_item(0x100, 1, true);
        self.items_by_byte[0x100] = Some(end_idx);

        let eof_idx = self.create_new_item(0x101, 1, true);
        self.items_by_byte[0x101] = Some(eof_idx);

        // Now sort the entire list by weight using insertion sort
        // Build a temporary sorted list
        let mut sorted_items: Vec<(usize, u32)> = Vec::new();
        let mut curr = self.first;
        while let Some(idx) = curr {
            sorted_items.push((idx, self.items[idx].weight));
            curr = self.items[idx].next;
        }

        // Sort by weight (DESCENDING - highest weight first)
        // This matches StormLib's organization where pLast points to lowest weight
        sorted_items.sort_by_key(|&(_, weight)| std::cmp::Reverse(weight));

        // Rebuild the linked list in sorted order
        self.first = None;
        self.last = None;

        for &(idx, _) in &sorted_items {
            // Clear existing links
            self.items[idx].prev = None;
            self.items[idx].next = None;

            // Add to the end of the new list
            if self.first.is_none() {
                self.first = Some(idx);
                self.last = Some(idx);
            } else {
                self.items[idx].prev = self.last;
                if let Some(last_idx) = self.last {
                    self.items[last_idx].next = Some(idx);
                }
                self.last = Some(idx);
            }
        }

        log::debug!("Built initial list with {} leaf nodes", self.items.len());

        // Debug: Print the linked list order
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("Initial linked list (first -> last):");
            let mut curr = self.first;
            let mut count = 0;
            while let Some(idx) = curr {
                if count < 5 || count >= self.items.len() - 5 {
                    log::trace!(
                        "  [{}] idx={}, value=0x{:02X}, weight={}",
                        count,
                        idx,
                        self.items[idx].decompressed_value,
                        self.items[idx].weight
                    );
                } else if count == 5 {
                    log::trace!("  ...");
                }
                curr = self.items[idx].next;
                count += 1;
            }
        }

        // Now we need to build the tree
        // IMPORTANT: After reviewing StormLib more carefully:
        // - The list is sorted DESCENDING (highest weight first, lowest weight last)
        // - pLast points to the LOWEST weight node
        // - We start from pLast and use pPrev to go towards higher weights
        // - This way we pair the lowest weight nodes first (correct for Huffman)
        let mut child_lo = self.last;
        let mut internal_nodes = 0;
        // Max weight is at the beginning of the list (descending order)
        let mut max_weight = if let Some(first_idx) = self.first {
            self.items[first_idx].weight
        } else {
            0
        };

        // Work as long as both children are valid
        while let Some(lo_idx) = child_lo {
            // Get the previous child (pPrev points to higher weight in descending list)
            let child_hi = self.items[lo_idx].prev;
            if child_hi.is_none() {
                log::debug!(
                    "Tree building stopped: no more pairs (created {internal_nodes} internal nodes)"
                );
                break; // Can't create a parent with only one child
            }
            let hi_idx = child_hi.unwrap();

            log::trace!(
                "Building parent for children: lo={} (w={}), hi={} (w={})",
                lo_idx,
                self.items[lo_idx].weight,
                hi_idx,
                self.items[hi_idx].weight
            );

            // Create new parent item for the children
            let parent_weight = self.items[hi_idx].weight + self.items[lo_idx].weight;
            let parent_idx = self.create_new_item(0xFFFFFFFFu32, parent_weight, true);
            internal_nodes += 1;

            // Link both child items to their new parent
            self.items[lo_idx].parent = Some(parent_idx);
            self.items[hi_idx].parent = Some(parent_idx);
            self.items[parent_idx].child_lo = Some(lo_idx);

            // IMPORTANT: Save the next child BEFORE fixup
            // In StormLib: pChildLo = pChildHi->pPrev
            let next_child = self.items[hi_idx].prev;

            // Fixup the item's position by its weight
            max_weight = self.fixup_item_pos_by_weight(parent_idx, max_weight);

            // Continue from where we left off
            // In StormLib, they just continue with pChildHi->pPrev
            // The paired nodes are effectively out of consideration because they have parents
            child_lo = next_child;

            log::trace!("Next iteration will start from: {child_lo:?}");
        }

        log::debug!(
            "Tree building complete: {} total items ({} leaf + {} internal)",
            self.items.len(),
            self.items.len() - internal_nodes,
            internal_nodes
        );

        // Initialize the MinValidValue to 1, which invalidates all quick-link items
        self.min_valid_value = 1;
        Ok(())
    }

    fn decode_one_byte(&mut self, reader: &mut BitReader<'_>) -> Result<u32> {
        // Try quick links first
        let item_link_index = reader.peek_7_bits().unwrap_or(0) as usize;
        let has_item_link = item_link_index < LINK_ITEM_COUNT;

        // Check if quick link is valid
        let mut item_idx = if has_item_link
            && self.quick_links[item_link_index].valid_value >= self.min_valid_value
        {
            // If that item needs less than 7 bits, we can get decompressed value directly
            if self.quick_links[item_link_index].valid_bits <= 7 {
                reader.skip_bits(self.quick_links[item_link_index].valid_bits);
                return Ok(self.quick_links[item_link_index].decompressed_value);
            }

            // Otherwise skip 7 bits and use the stored item
            reader.skip_bits(7);
            self.quick_links[item_link_index].item_index
        } else {
            // Start from the root (first item)
            self.first
        };

        // Check if we have a valid starting point
        if item_idx.is_none() {
            return Err(Error::compression("Empty Huffman tree"));
        }

        let mut item_link: Option<usize> = None;
        let mut bit_count = 0;

        // Step down the tree until we find a terminal item
        while let Some(idx) = item_idx {
            let item = &self.items[idx];

            // If this is a leaf node (no children), we found our value
            if item.child_lo.is_none() {
                break;
            }

            // Get next bit to decide which child to traverse
            let bit_value = reader.get_bit()?;
            bit_count += 1;

            // In StormLib:
            // If bit is 1: go to pItem->pChildLo->pPrev (higher weight child)
            // If bit is 0: go to pItem->pChildLo (lower weight child)
            let child_lo_idx = item.child_lo.unwrap();
            item_idx = if bit_value != 0 {
                // Get the previous sibling of child_lo (higher weight)
                self.items[child_lo_idx].prev
            } else {
                // Get child_lo directly (lower weight)
                Some(child_lo_idx)
            };

            // Remember item for quick link at depth 7
            if bit_count == 7 {
                item_link = item_idx;
            }
        }

        // We should have a valid item now
        let final_idx =
            item_idx.ok_or_else(|| Error::compression("Invalid Huffman tree traversal"))?;
        let decompressed_value = self.items[final_idx].decompressed_value;

        // Update quick link if needed
        if has_item_link && self.quick_links[item_link_index].valid_value < self.min_valid_value {
            if bit_count > 7 {
                // Store pointer to tree item for faster access
                self.quick_links[item_link_index].valid_value = self.min_valid_value;
                self.quick_links[item_link_index].valid_bits = bit_count;
                self.quick_links[item_link_index].item_index = item_link;
            } else if bit_count > 0 {
                // Store decompressed value directly
                let mut index = item_link_index;
                if bit_count < 7 {
                    index &= (0xFFFFFFFFu32 >> (32 - bit_count)) as usize;
                }

                while index < LINK_ITEM_COUNT {
                    self.quick_links[index].valid_value = self.min_valid_value;
                    self.quick_links[index].valid_bits = bit_count;
                    self.quick_links[index].decompressed_value = decompressed_value;
                    index += 1 << bit_count;
                }
            }
        }

        Ok(decompressed_value)
    }
}

/// Huffman decompression function following StormLib's algorithm
pub(crate) fn decompress(data: &[u8], expected_size: usize) -> Result<Vec<u8>> {
    if data.is_empty() {
        return Ok(Vec::new());
    }

    log::debug!(
        "Huffman decompress input: {} bytes, expected: {}, first 16 bytes: {:02X?}",
        data.len(),
        expected_size,
        &data[..std::cmp::min(16, data.len())]
    );

    let mut reader = BitReader::new(data);
    let mut output = Vec::with_capacity(expected_size);

    // Get compression type from the first byte
    let compression_type = reader.get_8_bits()?;

    log::debug!("Huffman compression type: 0x{compression_type:02X}");

    // Build Huffman tree
    let mut tree = HuffmanTree::new();
    tree.build_tree(compression_type)?;

    log::debug!("Huffman tree built with {} items", tree.items.len());

    // Decompress data
    let mut decoded_count = 0;
    loop {
        let decoded_value = tree.decode_one_byte(&mut reader)?;
        decoded_count += 1;

        log::trace!("Huffman decoded byte {decoded_count}: value=0x{decoded_value:03X}");

        // Check for end of stream marker
        if decoded_value == 0x100 {
            log::debug!("Huffman hit end marker after {decoded_count} symbols");
            break;
        }

        // Check for error
        if decoded_value == HUFF_DECOMPRESS_ERROR {
            return Err(Error::compression("Huffman decompression error"));
        }

        // Handle tree modification marker
        if decoded_value == 0x101 {
            // Read the next byte directly
            let next_byte = reader.get_8_bits()?;
            output.push(next_byte as u8);
            // Tree modification would happen here in full implementation
            continue;
        }

        // Regular data byte
        if decoded_value > 255 {
            return Err(Error::compression("Invalid Huffman decoded value"));
        }

        output.push(decoded_value as u8);

        // Stop if we've reached expected size
        if output.len() >= expected_size {
            break;
        }
    }

    log::debug!(
        "Huffman decompress output: {} bytes, first 16 bytes: {:02X?}",
        output.len(),
        &output[..std::cmp::min(16, output.len())]
    );

    Ok(output)
}

/// Huffman compression stub - not needed for reading MPQ archives
pub(crate) fn compress(_data: &[u8]) -> Result<Vec<u8>> {
    // Compression is not implemented as it's not needed for reading MPQ archives
    Err(Error::compression(
        "Huffman compression not implemented - only decompression is available",
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_huffman_empty_data() {
        assert!(decompress(&[], 0).is_ok());
    }

    #[test]
    fn test_bit_reader() {
        let data = vec![0b10101100, 0b11110000];
        let mut reader = BitReader::new(&data);

        // Read bits one by one (LSB first)
        assert_eq!(reader.get_bit().unwrap(), 0); // bit 0
        assert_eq!(reader.get_bit().unwrap(), 0); // bit 1
        assert_eq!(reader.get_bit().unwrap(), 1); // bit 2
        assert_eq!(reader.get_bit().unwrap(), 1); // bit 3
        assert_eq!(reader.get_bit().unwrap(), 0); // bit 4
        assert_eq!(reader.get_bit().unwrap(), 1); // bit 5
        assert_eq!(reader.get_bit().unwrap(), 0); // bit 6
        assert_eq!(reader.get_bit().unwrap(), 1); // bit 7
    }
}