File: gentee_installer.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (920 lines) | stat: -rw-r--r-- 25,467 bytes parent folder | download | duplicates (2)
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "common/debug.h"
#include "common/endian.h"
#include "common/stream.h"
#include "common/bufferedstream.h"
#include "common/substream.h"

#include "common/compression/gentee_installer.h"

namespace Common {

namespace GenteeInstaller {

struct HuffmanTreeNode {
	HuffmanTreeNode();

	HuffmanTreeNode *_parent;
	HuffmanTreeNode *_children[2];

	// NOTE: This must be signed! The decoder uses a broken normalization algorithm which halves all frequency
	// counts (instead of only halving leaf counts and recomputing parent nodes), which causes parent nodes
	// to desync if both children have odd frequencies.  This can cause the rebalancing algorithm to assign
	// negative numbers to frequencies, which in turn affects other comparisons through the decoder.
	//
	// We need to accurately replicate this bug to get the correct decode behavior.
	int32 _freq;

	uint16 _symbol;
};

HuffmanTreeNode::HuffmanTreeNode() : _parent(nullptr), _children{nullptr, nullptr}, _freq(0), _symbol(0) {
}

class HuffmanTree {
public:
	HuffmanTreeNode *_treeRoot;
	HuffmanTreeNode *_nodes;

	void incrementFreqCount(uint16 symbol);

protected:
	void initTree(HuffmanTreeNode *nodes, uint16 numLeafs);

private:
	void buildTree();
	static void rebalanceTree(HuffmanTreeNode *entry, HuffmanTreeNode *entryParentSibling);

	uint32 _numNodes;
	int32 _maxFreq;
	uint16 _numLeafs;
};

void HuffmanTree::buildTree() {
	HuffmanTreeNode *entries = _nodes;

	uint32 numResultingNodes = _numLeafs * 2 - 1;
	for (uint32 i = 0; i < numResultingNodes; i++)
		entries[i]._parent = nullptr;

	for (uint32 nextNode = _numLeafs; nextNode < numResultingNodes; nextNode++) {
		HuffmanTreeNode *lowest = nullptr;
		HuffmanTreeNode *secondLowest = nullptr;

		for (uint32 ci = 0; ci < nextNode; ci++) {
			HuffmanTreeNode *candidate = entries + ci;

			if (candidate->_parent == nullptr) {
				if (lowest == nullptr)
					lowest = candidate;
				else {
					if (candidate->_freq < lowest->_freq) {
						secondLowest = lowest;
						lowest = candidate;
					} else if (secondLowest == nullptr || candidate->_freq < secondLowest->_freq)
						secondLowest = candidate;
				}
			}
		}

		HuffmanTreeNode *newEntry = entries + nextNode;
		newEntry->_freq = lowest->_freq + secondLowest->_freq;
		newEntry->_symbol = nextNode;
		newEntry->_children[0] = lowest;
		newEntry->_children[1] = secondLowest;
		lowest->_parent = newEntry;
		secondLowest->_parent = newEntry;
	}

	_numNodes = numResultingNodes;
	_treeRoot = entries + numResultingNodes - 1;
}

void HuffmanTree::incrementFreqCount(uint16 symbol) {
	for (HuffmanTreeNode *checkEntry = _nodes + symbol; checkEntry; checkEntry = checkEntry->_parent) {
		HuffmanTreeNode *entryParent = checkEntry->_parent;

		if (checkEntry->_parent) {
			HuffmanTreeNode *parentOfParent = entryParent->_parent;

			if (parentOfParent) {
				HuffmanTreeNode *entryParentSibling = parentOfParent->_children[0];

				if (entryParent == entryParentSibling)
					entryParentSibling = parentOfParent->_children[1];

				if (entryParentSibling->_freq <= checkEntry->_freq)
					rebalanceTree(checkEntry, entryParentSibling);
			}
		}
		checkEntry->_freq = checkEntry->_freq + 1;
	}

	if (_maxFreq <= _treeRoot->_freq) {
		HuffmanTreeNode *entries = _nodes;

		for (uint i = 0; i < _numNodes; i++)
			entries[i]._freq >>= 1;
	}
}

void HuffmanTree::rebalanceTree(HuffmanTreeNode *entry, HuffmanTreeNode *entryParentSibling) {
	for (uint pass = 0; pass < 2; pass++) {
		HuffmanTreeNode *entryParent = entry->_parent;

		HuffmanTreeNode *entryParentChild0 = entryParent->_children[0];
		HuffmanTreeNode *entrySibling = entryParentChild0;

		if (entry == entryParentChild0)
			entrySibling = entryParent->_children[1];

		HuffmanTreeNode *entryParentSiblingHighestFreqChild = entryParentSibling->_children[0];
		if (entryParentSiblingHighestFreqChild && entryParentSiblingHighestFreqChild->_freq <= entryParentSibling->_children[1]->_freq)
			entryParentSiblingHighestFreqChild = entryParentSibling->_children[1];

		if (entry == entryParentChild0)
			entryParent->_children[0] = entryParentSibling;
		else
			entryParent->_children[1] = entryParentSibling;

		HuffmanTreeNode *entryParentParent = entryParent->_parent;

		if (entryParentParent->_children[0] == entryParentSibling)
			entryParentParent->_children[0] = entry;
		else
			entryParentParent->_children[1] = entry;

		entry->_parent = entryParentParent;
		entryParentSibling->_parent = entryParent;

		if (pass > 0 || entryParentSiblingHighestFreqChild == nullptr || entryParentSiblingHighestFreqChild->_freq <= entrySibling->_freq)
			break;

		entryParentSibling->_freq = entryParentSibling->_freq + entrySibling->_freq - entryParentSiblingHighestFreqChild->_freq;
		entry = entryParentSiblingHighestFreqChild;
		entryParentSibling = entrySibling;
	}
}

void HuffmanTree::initTree(HuffmanTreeNode *nodes, uint16 numLeafs) {

	_numLeafs = numLeafs;
	_nodes = nodes;
	_maxFreq = 512;

	for (uint16 i = 0; i < numLeafs; i++) {
		HuffmanTreeNode *entry = &nodes[i];
		entry->_symbol = i;
		entry->_freq = i + 1;
	}
	buildTree();
}

template<uint TNumLeafs>
class HuffmanTreePresized : public HuffmanTree {
public:
	HuffmanTreePresized();

	void reset();

private:
	HuffmanTreeNode _preallocNodes[TNumLeafs * 2];
};

template<uint TNumLeafs>
HuffmanTreePresized<TNumLeafs>::HuffmanTreePresized() {
	reset();
}

template<uint TNumLeafs>
void HuffmanTreePresized<TNumLeafs>::reset() {
	initTree(_preallocNodes, TNumLeafs);
}

class DecompressorState
{
public:
	explicit DecompressorState(Common::ReadStream *inputStream);

	void resetEverything();
	void resetBitstream();

	uint decompressBytes(void *dest, uint size);

private:
	static const uint kWindowSize = 32767;
	static const uint kMatchHistorySize = 4;
	static const uint kNumMatchVLCs = 30;

	HuffmanTreePresized<274> _codeTree;
	HuffmanTreePresized<34> _offsetTree;
	HuffmanTreePresized<237> _lengthTree;

	uint32 _matchOffsetHistory[kMatchHistorySize];

	uint16 _windowOffset;
	byte _window[kWindowSize];

	Common::ReadStream *_inputStream;

	static const byte g_matchVLCLengths[kNumMatchVLCs];
	uint16 _matchVLCOffsets[kNumMatchVLCs];

private:
	uint16 decodeDynamicHuffmanValue(HuffmanTree *tree);
	void recordMatchOffset(uint matchOffset);
	byte readBit();
	uint16 readBits(uint16 numBits);
	void emitByte(void *dest, byte b);

	uint _matchReadPos;
	uint _matchRemaining;

	byte _bitstreamByte;
	byte _bitstreamBitsRemaining;
	bool _failed;
};

DecompressorState::DecompressorState(Common::ReadStream *inputStream)
	: _inputStream(inputStream), _bitstreamBitsRemaining(0), _bitstreamByte(0), _matchRemaining(0), _matchReadPos(0), _failed(false), _matchOffsetHistory{0, 0, 0, 0}, _windowOffset(0) {
	resetEverything();
}

void DecompressorState::resetEverything() {
	resetBitstream();

	for (byte &b : _window)
		b = 0;

	_windowOffset = 0;

	uint16 nextValue = 0;
	for (int i = 0; i < 30; i++) {
		_matchVLCOffsets[i] = nextValue;
		nextValue = nextValue + (1 << (g_matchVLCLengths[i] & 0x1f));
	}

	for (uint32 i = 0; i < 4; i++)
		_matchOffsetHistory[i] = i;

	_codeTree.reset();
	_offsetTree.reset();
	_lengthTree.reset();

	_failed = false;
}

void DecompressorState::resetBitstream() {
	_bitstreamBitsRemaining = 0;
	_bitstreamByte = 0;
}


uint DecompressorState::decompressBytes(void *dest, uint size) {
	uint remaining = size;

	while (remaining > 0) {
		if (_failed)
			break;

		if (_matchRemaining > 0) {
			if (_matchReadPos == kWindowSize)
				_matchReadPos = 0;

			emitByte(dest, _window[_matchReadPos]);
			dest = static_cast<byte *>(dest) + 1;
			remaining--;
			_matchRemaining--;
			_matchReadPos++;
			continue;
		} else {
			uint16 code = decodeDynamicHuffmanValue(&_codeTree);

			if (code < 256) {
				if (_failed)
					break;

				emitByte(dest, static_cast<byte>(code));
				dest = static_cast<byte *>(dest) + 1;
				remaining--;
			} else {
				uint matchLength = 0;
				if (code > 272)
					matchLength = decodeDynamicHuffmanValue(&_lengthTree) + 20;
				else
					matchLength = code - 253;

				code = decodeDynamicHuffmanValue(&_offsetTree);

				uint matchOffset = 0;
				if (code < 30) {
					// Coded offset
					matchOffset = readBits(g_matchVLCLengths[code]) + _matchVLCOffsets[code];
				} else {
					// Historic offset
					matchOffset = _matchOffsetHistory[code - 30];
				}

				uint backDistance = matchLength + matchOffset;
				_matchReadPos = _windowOffset;

				while (_matchReadPos < backDistance)
					_matchReadPos += kWindowSize;

				_matchReadPos -= backDistance;
				_matchRemaining = matchLength;

				recordMatchOffset(matchOffset);
			}
		}
	}

	return size - remaining;
}

uint16 DecompressorState::decodeDynamicHuffmanValue(HuffmanTree *tree) {
	HuffmanTreeNode *node = tree->_treeRoot;
	while (node->_children[0] != nullptr)
		node = node->_children[readBit()];

	tree->incrementFreqCount(node->_symbol);
	return node->_symbol;
}

byte DecompressorState::readBit() {
	if (_bitstreamBitsRemaining == 0) {
		if (_failed)
			return 0;

		if (!_inputStream->read(&_bitstreamByte, 1)) {
			_failed = true;
			return 0;
		}

		_bitstreamBitsRemaining = 7;
	} else
		_bitstreamBitsRemaining--;

	byte bit = _bitstreamByte >> 7;
	_bitstreamByte <<= 1;
	return bit;
}

uint16 DecompressorState::readBits(uint16 numBits) {
	uint16 result = 0;
	uint16 bitToInsert = 1;

	while (numBits > 0) {
		if (readBit())
			result |= bitToInsert;

		bitToInsert <<= 1;
		numBits--;
	}

	return result;
}

void DecompressorState::emitByte(void *dest, byte b) {
	*static_cast<byte *>(dest) = b;

	_window[_windowOffset] = b;
	_windowOffset++;

	if (_windowOffset == kWindowSize)
		_windowOffset = 0;
}

void DecompressorState::recordMatchOffset(uint matchOffset) {
	uint expungeIndex = kMatchHistorySize - 1;

	for (uint i = 0; i < kMatchHistorySize - 1u; i++) {
		if (_matchOffsetHistory[i] == matchOffset) {
			expungeIndex = i;
			break;
		}
	}

	if (expungeIndex == 0)
		return;

	for (uint i = 0; i < expungeIndex; i++)
		_matchOffsetHistory[expungeIndex - i] = _matchOffsetHistory[expungeIndex - i - 1];

	_matchOffsetHistory[0] = matchOffset;
}

const byte DecompressorState::g_matchVLCLengths[DecompressorState::kNumMatchVLCs] = {
	0, 1, 1, 2, 2,
	2, 3, 3, 3, 3,
	4, 4, 5, 5, 6,
	6, 7, 7, 8, 8,
	9, 9, 10, 10, 11,
	11, 12, 12, 13, 13
};

class DecompressingStream : public Common::SeekableReadStream {
public:
	DecompressingStream(Common::SeekableReadStream *baseStream, uint32 decompressedSize);
	~DecompressingStream();

	int64 pos() const override;
	int64 size() const override;
	bool seek(int64 offset, int whence) override;
	bool skip(uint32 offset) override;
	bool eos() const override;
	uint32 read(void *dataPtr, uint32 dataSize) override;
	bool err() const override;
	void clearErr() override;

private:
	bool rewind();

	DecompressorState _decomp;

	Common::SeekableReadStream *_baseStream;

	uint32 _pos;
	uint32 _decompressedSize;
	bool _eosFlag;
	bool _errFlag;
};

DecompressingStream::DecompressingStream(Common::SeekableReadStream *baseStream, uint32 decompressedSize)
	: _baseStream(baseStream), _decompressedSize(decompressedSize), _pos(0), _eosFlag(false), _errFlag(false), _decomp(baseStream) {
}

DecompressingStream::~DecompressingStream() {
	delete _baseStream;
}

int64 DecompressingStream::pos() const {
	return _pos;
}

int64 DecompressingStream::size() const {
	return _decompressedSize;
}

bool DecompressingStream::seek(int64 offset, int whence) {
	switch (whence) {
	case SEEK_SET:
		if (offset == _pos)
			return true;

		if (offset < 0)
			return false;

		if (offset == 0)
			return rewind();

		if (offset > static_cast<int64>(_decompressedSize))
			return false;

		if (offset == static_cast<int64>(_decompressedSize)) {
			// Just set position to EOF
			_pos = _decompressedSize;
			return true;
		}

		if (offset < static_cast<int64>(_pos)) {
			if (!rewind())
				return false;
		}

		return skip(static_cast<uint32>(offset) - _pos);
	case SEEK_END:
		return seek(static_cast<int64>(_decompressedSize) + offset, SEEK_SET);
	case SEEK_CUR:
		return seek(static_cast<int64>(_pos) + offset, SEEK_SET);
	default:
		return false;
	}
}

bool DecompressingStream::skip(uint32 offset) {
	const uint kSkipBufSize = 1024;
	byte skipBuf[kSkipBufSize];

	while (offset > 0) {
		uint32 skipAmount = kSkipBufSize;
		if (skipAmount > offset)
			skipAmount = offset;

		uint32 amountRead = read(skipBuf, skipAmount);
		if (amountRead != skipAmount)
			return false;

		offset -= amountRead;
	}

	return true;
}

bool DecompressingStream::eos() const {
	return _eosFlag;
}

uint32 DecompressingStream::read(void *dataPtr, uint32 dataSize) {
	if (_errFlag)
		return 0;

	uint32 bytesAvailable = _decompressedSize - _pos;

	if (dataSize > bytesAvailable) {
		_eosFlag = true;
		dataSize = bytesAvailable;
	}

	if (dataSize == 0)
		return 0;

	uint32 numBytesDecompressed = _decomp.decompressBytes(dataPtr, dataSize);
	if (numBytesDecompressed < dataSize)
		_errFlag = true;

	_pos += numBytesDecompressed;

	return numBytesDecompressed;
}

bool DecompressingStream::err() const {
	return _errFlag;
}

void DecompressingStream::clearErr() {
	_errFlag = false;
	_eosFlag = false;
	_baseStream->clearErr();
}

bool DecompressingStream::rewind() {
	if (!_baseStream->seek(0)) {
		_errFlag = true;
		return false;
	}

	_decomp.resetEverything();
	_pos = 0;
	return true;
}

class ArchiveItem : public Common::ArchiveMember {
public:
	ArchiveItem(Common::SeekableReadStream *stream, Common::Mutex *guardMutex, const Common::Path &path, int64 filePos, uint compressedSize, uint decompressedSize, bool isCompressed);

	Common::SeekableReadStream *createReadStream() const override;
	Common::SeekableReadStream *createReadStreamForAltStream(Common::AltStreamType altStreamType) const override;
	Common::String getName() const override { return getFileName(); }
	Common::Path getPathInArchive() const override { return _path; }
	Common::String getFileName() const override { return _path.getLastComponent().toString(); }

private:
	Common::SeekableReadStream *_stream;
	Common::Mutex *_guardMutex;
	Common::Path _path;
	int64 _filePos;
	uint _compressedSize;
	uint _decompressedSize;
	bool _isCompressed;
};

ArchiveItem::ArchiveItem(Common::SeekableReadStream *stream, Common::Mutex *guardMutex, const Common::Path &path, int64 filePos, uint compressedSize, uint decompressedSize, bool isCompressed)
	: _stream(stream), _guardMutex(guardMutex), _path(path), _filePos(filePos), _compressedSize(compressedSize), _decompressedSize(decompressedSize), _isCompressed(isCompressed) {
}

Common::SeekableReadStream *ArchiveItem::createReadStream() const {
	Common::SeekableReadStream *sliceSubstream = nullptr;

	if (_guardMutex)
		sliceSubstream = new Common::SafeMutexedSeekableSubReadStream(_stream, static_cast<uint32>(_filePos), static_cast<uint32>(_filePos) + _compressedSize, DisposeAfterUse::NO, *_guardMutex);
	else
		sliceSubstream = new Common::SeekableSubReadStream(_stream, static_cast<uint32>(_filePos), static_cast<uint32>(_filePos) + _compressedSize, DisposeAfterUse::NO);

	// Add buffering since seekable substreams can be extremely slow!
	sliceSubstream = Common::wrapBufferedSeekableReadStream(sliceSubstream, 4096, DisposeAfterUse::YES);

	if (_isCompressed)
		return new DecompressingStream(sliceSubstream, _decompressedSize);
	else
		return sliceSubstream;
}

Common::SeekableReadStream *ArchiveItem::createReadStreamForAltStream(Common::AltStreamType altStreamType) const {
	return nullptr;
}

class PackageArchive : public Common::Archive {
public:
	explicit PackageArchive(Common::SeekableReadStream *stream);
	~PackageArchive();

	bool load(const char *prefix);

	bool hasFile(const Common::Path &path) const override;
	int listMembers(Common::ArchiveMemberList &list) const override;
	int listMatchingMembers(Common::ArchiveMemberList &list, const Common::Path &pattern, bool matchPathComponents) const override;
	const Common::ArchiveMemberPtr getMember(const Common::Path &path) const override;
	Common::SeekableReadStream *createReadStreamForMember(const Common::Path &path) const override;

protected:
	virtual Common::Mutex *getGuardMutex();

private:
	bool decodeDataChunk(DecompressorState *decompState, Common::Array<byte> &data);
	static Common::String normalizePath(const Common::Path &path);

	Common::Array<Common::SharedPtr<ArchiveItem> > _items;
	Common::HashMap<Common::Path, uint, Common::Path::IgnoreCase_Hash, Common::Path::IgnoreCase_EqualTo> _pathToItemIndex;

	Common::SeekableReadStream *_stream;
};

PackageArchive::PackageArchive(Common::SeekableReadStream *stream) : _stream(stream) {
}

PackageArchive::~PackageArchive() {
	delete _stream;
}

bool PackageArchive::load(const char *prefix) {
	byte pakFileSizeBytes[4];

	int64 pakFileStartPos = _stream->pos();
	int64 maxPakFileSize = _stream->size() - pakFileStartPos;

	if (_stream->read(pakFileSizeBytes, 4) != 4) {
		warning("GenteeInstaller::PackageArchive::load: Couldn't read pak file size declaration");
		return false;
	}

	uint32 pakFileSize = READ_LE_UINT32(pakFileSizeBytes);

	if (static_cast<int64>(pakFileSize) < maxPakFileSize) {
		warning("GenteeInstaller::PackageArchive::load: Pak file size was larger than would be possible");
		return false;
	}

	if (pakFileStartPos != 0 || maxPakFileSize != pakFileSize) {
		_stream = new Common::SeekableSubReadStream(_stream, pakFileStartPos, static_cast<uint32>(pakFileStartPos) + pakFileSize, DisposeAfterUse::YES);
		if (!_stream->seek(4)) {
			warning("GenteeInstaller::PackageArchive::load: Couldn't reset pak position");
			return false;
		}
	}

	byte pakFileHeader[16];
	if (_stream->read(pakFileHeader, 16) != 16) {
		warning("GenteeInstaller::PackageArchive::load: Couldn't load pak header");
		return false;
	}

	Common::ScopedPtr<DecompressorState> cmdContextPtr(new DecompressorState(_stream));

	DecompressorState *cmdContext = cmdContextPtr.get();

	Common::Array<byte> firstChunk;

	if (!decodeDataChunk(cmdContext, firstChunk))
		return false;

	if (firstChunk.size() < 3) {
		warning("GenteeInstaller::PackageArchive::load: First chunk is malformed");
		return false;
	}

	bool allFilesAreStored = (firstChunk[0] != 0);

	// The second chunk appears to not be a commandlet either, should figure out what it is

	while (_stream->pos() < _stream->size()) {
		Common::Array<byte> commandletChunk;

		if (!decodeDataChunk(cmdContext, commandletChunk))
			return false;

		if (commandletChunk.size() < 3) {
			warning("GenteeInstaller::PackageArchive::load: Commandlet was malformed");
			return false;
		}

		uint16 commandletCode = READ_LE_UINT16(&commandletChunk[0]);

		if (commandletCode == 0x87f4) {
			// Unpack file commandlet
			if (commandletChunk.size() < 36 || commandletChunk.back() != 0) {
				warning("GenteeInstaller::PackageArchive::load: File commandlet was malformed");
				return false;
			}

			Common::String fileName = Common::String(reinterpret_cast<const char *>(&commandletChunk[34]));

			bool isCompressed = (!allFilesAreStored) && (commandletChunk[28] != 0);

			int64 dataStart = _stream->pos();
			int64 dataEnd = dataStart;
			uint32 decompressedSize = 0;

			if (isCompressed) {
				// Extremely annoying: The compressed data size isn't stored, so we must decompress the entire file
				// to find the next commandlet
				Common::ScopedPtr<DecompressorState> fileCtx(new DecompressorState(_stream));

				byte decompressedSizeBytes[4];
				if (_stream->read(decompressedSizeBytes, 4) != 4) {
					warning("GenteeInstaller::PackageArchive::load: Decompressed file size was malformed");
					return false;
				}

				decompressedSize = READ_LE_UINT32(decompressedSizeBytes);
				dataStart += 4;

				const uint kSkipBufSize = 1024;

				byte skipBuf[1024];
				uint32 skipRemaining = decompressedSize;
				while (skipRemaining > 0) {
					uint32 amountToSkip = skipRemaining;
					if (amountToSkip > kSkipBufSize)
						amountToSkip = kSkipBufSize;

					if (fileCtx->decompressBytes(skipBuf, amountToSkip) != amountToSkip) {
						warning("GenteeInstaller::PackageArchive::load: Couldn't decompress file data to skip it");
						return false;

					}

					skipRemaining -= amountToSkip;
				}

				dataEnd = _stream->pos();
			} else {
				decompressedSize = READ_LE_UINT32(&commandletChunk[7]);
				if (!_stream->skip(decompressedSize)) {
					warning("GenteeInstaller::PackageArchive::load: Failed to skip uncompressed file data");
					return false;
				}
				dataEnd = _stream->pos();
			}

			debug(3, "GenteeInstaller: Detected %s item '%s' size %u at pos %u .. %u", (isCompressed ? "compressed" : "stored"), fileName.c_str(), static_cast<uint>(decompressedSize), static_cast<uint>(dataStart), static_cast<uint>(dataEnd));

			if (fileName.hasPrefix(prefix)) {
				fileName = fileName.substr(strlen(prefix));
				fileName.replace('\\', '/');
				Common::Path path(fileName, '/');

				Common::SharedPtr<ArchiveItem> item(new ArchiveItem(_stream, getGuardMutex(), path, dataStart, static_cast<uint>(dataEnd - dataStart), decompressedSize, isCompressed));

				_pathToItemIndex[path] = _items.size();

				_items.push_back(item);
			}
		}
	}

	return true;
}

bool PackageArchive::decodeDataChunk(DecompressorState *decompState, Common::Array<byte> &commandletData) {
	byte sizeBytes[4];
	if (_stream->read(sizeBytes, 4) != 4) {
		warning("GenteeInstaller::PackageArchive::load: Couldn't read commandlet size");
		return false;
	}

	uint32 size = READ_LE_UINT32(sizeBytes);

	if (size > 4 * 1024 * 1024) {
		warning("GenteeInstaller::PackageArchive::load: Commandlet was abnormally large, possibly corrupt data or a decompression bug");
		return false;
	}

	commandletData.resize(size);

	if (size > 0) {
		decompState->resetBitstream();
		if (decompState->decompressBytes(&commandletData[0], size) != size) {
			warning("GenteeInstaller::PackageArchive::load: Commandlet packet decompression failed");
			return false;
		}
	}

	return true;
}

Common::String PackageArchive::normalizePath(const Common::Path &path) {
	Common::String normalizedPath = path.toString();
	normalizedPath.toLowercase();
	return normalizedPath;
}

bool PackageArchive::hasFile(const Common::Path &path) const {
	return _pathToItemIndex.find(path) != _pathToItemIndex.end();
}

int PackageArchive::listMembers(Common::ArchiveMemberList &list) const {
	for (const Common::SharedPtr<ArchiveItem> &item : _items)
		list.push_back(item.staticCast<Common::ArchiveMember>());

	return _items.size();
}

int PackageArchive::listMatchingMembers(Common::ArchiveMemberList &list, const Common::Path &pattern, bool matchPathComponents) const {
	int matches = 0;
	const char *wildcardExclusions = matchPathComponents ? NULL : "/";

	for (const Common::SharedPtr<ArchiveItem> &item : _items) {
		if (normalizePath(item->getPathInArchive()).matchString(normalizePath(pattern), false, wildcardExclusions)) {
			list.push_back(item.staticCast<Common::ArchiveMember>());
			matches++;
		}
	}

	return matches;
}

const Common::ArchiveMemberPtr PackageArchive::getMember(const Common::Path &path) const {
	Common::HashMap<Common::Path, uint, Common::Path::IgnoreCase_Hash, Common::Path::IgnoreCase_EqualTo>::const_iterator it = _pathToItemIndex.find(path);
	if (it == _pathToItemIndex.end())
		return nullptr;

	return _items[it->_value].staticCast<Common::ArchiveMember>();
}

Common::SeekableReadStream *PackageArchive::createReadStreamForMember(const Common::Path &path) const {
	const Common::ArchiveMemberPtr member = getMember(path);

	if (!member)
		return nullptr;

	return member->createReadStream();
}

Common::Mutex *PackageArchive::getGuardMutex() {
	return nullptr;
}


class ThreadSafePackageArchive : public PackageArchive {
public:
	explicit ThreadSafePackageArchive(Common::SeekableReadStream *stream);

protected:
	Common::Mutex *getGuardMutex() override;

private:
	Common::Mutex _guardMutex;
};

ThreadSafePackageArchive::ThreadSafePackageArchive(Common::SeekableReadStream *stream) : PackageArchive(stream) {
}

Common::Mutex *ThreadSafePackageArchive::getGuardMutex() {
	return &_guardMutex;
}

} // End of namespace GenteeInstaller



Common::Archive *createGenteeInstallerArchive(Common::SeekableReadStream *stream, const char *prefixToRemove, bool threadSafe) {
	if (!prefixToRemove)
		prefixToRemove = "";

	GenteeInstaller::PackageArchive *archive = nullptr;

	if (threadSafe)
		archive = new GenteeInstaller::ThreadSafePackageArchive(stream);
	else
		archive = new GenteeInstaller::PackageArchive(stream);

	if (!archive->load(prefixToRemove)) {
		delete archive;
		return nullptr;
	}

	return archive;
}

} // End of namespace Common