summaryrefslogtreecommitdiff
path: root/util/nrv2b/nrv2b.c
blob: e341a7b61de8839f83fd82b1eb539fd17cd3ce6f (plain)
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
/**************************************************************
    Form adapted from lzhuf.c
    written by Haruyasu Yoshizaki 11/20/1988
    some minor changes 4/6/1989
    comments translated by Haruhiko Okumura 4/7/1989

    minor beautifications and adjustments for compiling under Linux
    by Markus Gutschke <gutschk@math.uni-muenster.de>
    						1997-01-27

    Modifications to allow use as a filter by Ken Yap
    <ken_yap@users.sourceforge.net>.

						1997-07-01

    Small mod to cope with running on big-endian machines
    by Jim Hague <jim.hague@acm.org)
						1998-02-06

    Make compression statistics report shorter
    by Ken Yap <ken_yap@users.sourceforge.net>.
						2001-04-25

    Replaced algorithm with nrv2b from ucl the compression
    library from upx.  That code is:
    Copyright (C) 1996-2002 Markus Franz Xaver Johannes Oberhumer
    And is distributed under the terms of the GPL.
    The conversion was performed 
    by Eric Biederman <ebiederman@lnxi.com>.
                                             20 August 2002
                                                
**************************************************************/
#define UCLPACK_COMPAT 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdint.h>
#include <limits.h>
#include <assert.h>
#if UCLPACK_COMPAT
#include <netinet/in.h>
#endif


#ifndef VERBOSE
#define Fprintf(x)
#define wterr     0
#else
#define Fprintf(x) fprintf x
#endif

#ifndef MAIN
extern
#endif
FILE  *infile, *outfile;

#if defined(ENCODE) || defined(DECODE)

#ifndef ENDIAN
#define ENDIAN   0
#endif
#ifndef BITSIZE
#define BITSIZE 32
#endif

static __inline__ __attribute__((noreturn)) void Error(char *message)
{
	Fprintf((stderr, "\n%s\n", message));
	exit(EXIT_FAILURE);
}

/* These will be a complete waste of time on a lo-endian */
/* system, but it only gets done once so WTF. */
static unsigned long i86ul_to_host(unsigned long ul)
{
	unsigned long res = 0;
	int i;
	union
	{
		unsigned char c[4];
		unsigned long ul;
	} u;

	u.ul = ul;
	for (i = 3; i >= 0; i--)
		res = (res << 8) + u.c[i];
	return res;
}

static unsigned long host_to_i86ul(unsigned long ul)
{
	int i;
	union
	{
		unsigned char c[4];
		unsigned long ul;
	} u;

	for (i = 0; i < 4; i++)
	{
		u.c[i] = ul & 0xff;
		ul >>= 8;
	}
	return u.ul;
}
#endif



#if UCLPACK_COMPAT
/* magic file header for compressed files */
static const unsigned char magic[8] =
{ 0x00, 0xe9, 0x55, 0x43, 0x4c, 0xff, 0x01, 0x1a };

#endif

#ifdef ENCODE
/********** NRV2B_99 compression **********/

#define N       (1024*1024ul)       /* size of ring buffer */
#define THRESHOLD       1           /* lower limit for match length */
#define F            2048           /* upper limit for match length */
#define M2_MAX_OFFSET                 0xd00

/* note: to use default values pass -1, i.e. initialize
 * this struct by a memset(x,0xff,sizeof(x)) */
struct ucl_compress_config
{
	int bb_endian;
	int bb_size;
	unsigned int max_offset;
	unsigned int max_match;
	int s_level;
	int h_level;
	int p_level;
	int c_flags;
	unsigned int m_size;
};

struct ucl_compress
{
	int init;

	unsigned int look;          /* bytes in lookahead buffer */
	
	unsigned int m_len;
	unsigned int m_off;
	
	unsigned int last_m_len;
	unsigned int last_m_off;
	
	const unsigned char *bp;
	const unsigned char *ip;
	const unsigned char *in;
	const unsigned char *in_end;
	unsigned char *out;
	
	uint32_t bb_b;
	unsigned bb_k;
	unsigned bb_c_endian;
	unsigned bb_c_s;
	unsigned bb_c_s8;
	unsigned char *bb_p;
	unsigned char *bb_op;
	
	struct ucl_compress_config conf;
	unsigned int *result;

	unsigned int textsize;      /* text size counter */
	unsigned int codesize;      /* code size counter */
	unsigned int printcount; /* counter for reporting progress every 1K
				    bytes */

	
	/* some stats */
	unsigned long lit_bytes;
	unsigned long match_bytes;
	unsigned long rep_bytes;
	unsigned long lazy;
};



#define getbyte(c)  ((c).ip < (c).in_end ? *((c).ip)++ : (-1))

#define UCL_E_OK               0
#define UCL_E_INVALID_ARGUMENT 1
#define UCL_E_OUT_OF_MEMORY    2
#define UCL_E_ERROR            3

/***********************************************************************
//
************************************************************************/

#define SWD_HSIZE	16384
#define SWD_MAX_CHAIN	2048

#define HEAD3(b,p) \
    (((0x9f5f*(((((uint32_t)b[p]<<5)^b[p+1])<<5)^b[p+2]))>>5) & (SWD_HSIZE-1))

#define HEAD2(b,p)      (b[p] ^ ((unsigned)b[p+1]<<8))
#define NIL2              UINT_MAX

struct ucl_swd
{
/* public - "built-in" */
	unsigned int n;
	unsigned int f;
	unsigned int threshold;
	
/* public - configuration */
	unsigned int max_chain;
	unsigned int nice_length;
	int use_best_off;
	unsigned int lazy_insert;
	
/* public - output */
	unsigned int m_len;
	unsigned int m_off;
	unsigned int look;
	int b_char;
#if defined(SWD_BEST_OFF)
	unsigned int best_off[ SWD_BEST_OFF ];
#endif
	
/* semi public */
	struct ucl_compress *c;
	unsigned int m_pos;
#if defined(SWD_BEST_OFF)
	unsigned int best_pos[ SWD_BEST_OFF ];
#endif
	
/* private */
	const uint8_t *dict;
	const uint8_t *dict_end;
	unsigned int dict_len;
	
/* private */
	unsigned int ip;                /* input pointer (lookahead) */
	unsigned int bp;                /* buffer pointer */
	unsigned int rp;                /* remove pointer */
	unsigned int b_size;
	
	unsigned char *b_wrap;
	
	unsigned int node_count;
	unsigned int first_rp;

	unsigned char b [ N + F + F ];
	unsigned int head3 [ SWD_HSIZE ];
	unsigned int succ3 [ N + F ];
	unsigned int best3 [ N + F ];
	unsigned int llen3 [ SWD_HSIZE ];
	unsigned int head2 [ 65536U ];
};

#define s_head3(s,key)        s->head3[key]


#if !defined( NDEBUG)
static void assert_match(const struct ucl_swd * swd, unsigned int m_len,
	unsigned int m_off )

{
	const struct ucl_compress *c = swd->c;
	unsigned int d_off;
	
	assert(m_len >= 2);
	if (m_off <= (unsigned int) (c->bp - c->in))
	{
		assert(c->bp - m_off + m_len < c->ip);
		assert(memcmp(c->bp, c->bp - m_off, m_len) == 0);
	}
	else
	{
		assert(swd->dict != NULL);
		d_off = m_off - (unsigned int) (c->bp - c->in);
		assert(d_off <= swd->dict_len);
		if (m_len > d_off)
		{
			assert(memcmp(c->bp, swd->dict_end - d_off, d_off) ==
				0);

			assert(c->in + m_len - d_off < c->ip);
			assert(memcmp(c->bp + d_off, c->in, m_len - d_off) ==
				0);

		}
		else
		{
			assert(memcmp(c->bp, swd->dict_end - d_off, m_len) ==
				0);

		}
	}
}
#else
#  define assert_match(a,b,c)   ((void)0)
#endif

/***********************************************************************
//
************************************************************************/


static
void swd_initdict(struct ucl_swd *s, const uint8_t *dict, unsigned int dict_len)

{
	s->dict = s->dict_end = NULL;
	s->dict_len = 0;

	if (!dict || dict_len <= 0)
		return;
	if (dict_len > s->n)
	{
		dict += dict_len - s->n;
		dict_len = s->n;
	}

	s->dict = dict;
	s->dict_len = dict_len;
	s->dict_end = dict + dict_len;
	memcpy(s->b,dict,dict_len);
	s->ip = dict_len;
}


static
void swd_insertdict(struct ucl_swd *s, unsigned int node, unsigned int len)
{
	unsigned int key;

	s->node_count = s->n - len;
	s->first_rp = node;

	while (len-- > 0)
	{
		key = HEAD3(s->b,node);
		s->succ3[node] = s_head3(s,key);
		s->head3[key] = (unsigned int)(node);
		s->best3[node] = (unsigned int)(s->f + 1);
		s->llen3[key]++;
		assert(s->llen3[key] <= s->n);

		key = HEAD2(s->b,node);
		s->head2[key] = (unsigned int)(node);

		node++;
	}
}

/***********************************************************************
//
************************************************************************/


static
int swd_init(struct ucl_swd *s, const uint8_t *dict, unsigned int dict_len)
{
	unsigned int i = 0;
	int c = 0;

	if (s->n == 0)
		s->n = N;
	if (s->f == 0)
		s->f = F;
	s->threshold = THRESHOLD;
	if (s->n > N || s->f > F)
		return UCL_E_INVALID_ARGUMENT;

	/* defaults */
	s->max_chain = SWD_MAX_CHAIN;
	s->nice_length = s->f;
	s->use_best_off = 0;
	s->lazy_insert = 0;

	s->b_size = s->n + s->f;
	if (s->b_size + s->f >= UINT_MAX)
		return UCL_E_ERROR;
	s->b_wrap = s->b + s->b_size;
	s->node_count = s->n;

	memset(s->llen3, 0, sizeof(s->llen3[0]) * SWD_HSIZE);
	for (i = 0; i < 65536U; i++)
		s->head2[i] = NIL2;

	s->ip = 0;
	swd_initdict(s,dict,dict_len);
	s->bp = s->ip;
	s->first_rp = s->ip;

	assert(s->ip + s->f <= s->b_size);

	s->look = (unsigned int) (s->c->in_end - s->c->ip);
	if (s->look > 0)
	{
		if (s->look > s->f)
			s->look = s->f;
		memcpy(&s->b[s->ip],s->c->ip,s->look);
		s->c->ip += s->look;
		s->ip += s->look;
	}
	if (s->ip == s->b_size)
		s->ip = 0;

	if (s->look >= 2 && s->dict_len > 0)
		swd_insertdict(s,0,s->dict_len);

	s->rp = s->first_rp;
	if (s->rp >= s->node_count)
		s->rp -= s->node_count;
	else
		s->rp += s->b_size - s->node_count;

	/* unused i */
	/* unused c */
	return UCL_E_OK;
}


static
void swd_exit(struct ucl_swd *s)
{
	/* unused s */

}

#define swd_pos2off(s,pos) \
	(s->bp > (pos) ? s->bp - (pos) : s->b_size - ((pos) - s->bp))

/***********************************************************************
//
************************************************************************/

static __inline__
void swd_getbyte(struct ucl_swd *s)
{
	int c;

	if ((c = getbyte(*(s->c))) < 0)
	{
		if (s->look > 0)
			--s->look;
	}
	else
	{
		s->b[s->ip] = (uint8_t)(c);
		if (s->ip < s->f)
			s->b_wrap[s->ip] = (uint8_t)(c);
	}
	if (++s->ip == s->b_size)
		s->ip = 0;
	if (++s->bp == s->b_size)
		s->bp = 0;
	if (++s->rp == s->b_size)
		s->rp = 0;
}
/***********************************************************************
// remove node from lists
************************************************************************/

static __inline__
void swd_remove_node(struct ucl_swd *s, unsigned int node)
{
	if (s->node_count == 0)
	{
		unsigned int key;
		
#ifdef UCL_DEBUG
		if (s->first_rp != UINT_MAX)
		{
			if (node != s->first_rp)
				printf("Remove %5d: %5d %5d %5d %5d %6d %6d\n",

					node, s->rp, s->ip, s->bp, s->first_rp,
					s->ip - node, s->ip - s->bp);
			assert(node == s->first_rp);
			s->first_rp = UINT_MAX;
		}
#endif
		
		key = HEAD3(s->b,node);
		assert(s->llen3[key] > 0);
		--s->llen3[key];
		
		key = HEAD2(s->b,node);
		assert(s->head2[key] != NIL2);
		if ((unsigned int) s->head2[key] == node)
			s->head2[key] = NIL2;
	}
	else
		--s->node_count;
}


/***********************************************************************
//
************************************************************************/


static
void swd_accept(struct ucl_swd *s, unsigned int n)
{
	assert(n <= s->look);

	if (n > 0) do
	{
		unsigned int key;

		swd_remove_node(s,s->rp);

		/* add bp into HEAD3 */
		key = HEAD3(s->b,s->bp);
		s->succ3[s->bp] = s_head3(s,key);
		s->head3[key] = (unsigned int)(s->bp);
		s->best3[s->bp] = (unsigned int)(s->f + 1);
		s->llen3[key]++;
		assert(s->llen3[key] <= s->n);

		/* add bp into HEAD2 */
		key = HEAD2(s->b,s->bp);
		s->head2[key] = (unsigned int)(s->bp);

		swd_getbyte(s);
	} while (--n > 0);
}

/***********************************************************************
//
************************************************************************/

static
void swd_search(struct ucl_swd *s, unsigned int node, unsigned int cnt)
{
	const unsigned char *p1;
	const unsigned char *p2;
	const unsigned char *px;

	unsigned int m_len = s->m_len;
	const unsigned char * b  = s->b;
	const unsigned char * bp = s->b + s->bp;
	const unsigned char * bx = s->b + s->bp + s->look;
	unsigned char scan_end1;
	
	assert(s->m_len > 0);
	
	scan_end1 = bp[m_len - 1];
	for ( ; cnt-- > 0; node = s->succ3[node])
	{
		p1 = bp;
		p2 = b + node;
		px = bx;
		
		assert(m_len < s->look);
		
		if (
			p2[m_len - 1] == scan_end1 &&
			p2[m_len] == p1[m_len] &&
			p2[0] == p1[0] &&
			p2[1] == p1[1])
		{
			unsigned int i;
			assert(memcmp(bp,&b[node],3) == 0);
			
			p1 += 2; p2 += 2;
			do {} while (++p1 < px && *p1 == *++p2);
			i = p1 - bp;
			
#ifdef UCL_DEBUG
			if (memcmp(bp,&b[node],i) != 0)
				printf("%5ld %5ld %02x%02x %02x%02x\n",
					(long)s->bp, (long) node,
					bp[0], bp[1], b[node], b[node+1]);
#endif
			assert(memcmp(bp,&b[node],i) == 0);
			
#if defined(SWD_BEST_OFF)
			if (i < SWD_BEST_OFF)
			{
				if (s->best_pos[i] == 0)
					s->best_pos[i] = node + 1;
			}
#endif
			if (i > m_len)
			{
				s->m_len = m_len = i;
				s->m_pos = node;
				if (m_len == s->look)
					return;
				if (m_len >= s->nice_length)
					return;
				if (m_len > (unsigned int) s->best3[node])
					return;
				scan_end1 = bp[m_len - 1];
			}
		}
	}
}

static int swd_search2(struct ucl_swd *s)
{
	unsigned int key;
	
	assert(s->look >= 2);
	assert(s->m_len > 0);
	
	key = s->head2[ HEAD2(s->b,s->bp) ];
	if (key == NIL2)
		return 0;
#ifdef UCL_DEBUG
	if (memcmp(&s->b[s->bp],&s->b[key],2) != 0)
		printf("%5ld %5ld %02x%02x %02x%02x\n", (long)s->bp, (long)key,
			s->b[s->bp], s->b[s->bp+1], s->b[key], s->b[key+1]);
#endif
	assert(memcmp(&s->b[s->bp],&s->b[key],2) == 0);
#if defined(SWD_BEST_OFF)
	if (s->best_pos[2] == 0)
		s->best_pos[2] = key + 1;
#endif
	
	if (s->m_len < 2)
	{
		s->m_len = 2;
		s->m_pos = key;
	}
	return 1;
}

/***********************************************************************
//
************************************************************************/

static
void swd_findbest(struct ucl_swd *s)
{
	unsigned int key;
	unsigned int cnt, node;
	unsigned int len;

	assert(s->m_len > 0);

	/* get current head, add bp into HEAD3 */
	key = HEAD3(s->b,s->bp);
	node = s->succ3[s->bp] = s_head3(s,key);
	cnt = s->llen3[key]++;
	assert(s->llen3[key] <= s->n + s->f);
	if (cnt > s->max_chain && s->max_chain > 0)
		cnt = s->max_chain;
	s->head3[key] = (unsigned int)(s->bp);

	s->b_char = s->b[s->bp];
	len = s->m_len;
	if (s->m_len >= s->look)
	{
		if (s->look == 0)
			s->b_char = -1;
		s->m_off = 0;
		s->best3[s->bp] = (unsigned int)(s->f + 1);
	}
	else
	{
		if (swd_search2(s))
			if (s->look >= 3)
				swd_search(s,node,cnt);
		if (s->m_len > len)
			s->m_off = swd_pos2off(s,s->m_pos);
		s->best3[s->bp] = (unsigned int)(s->m_len);

#if defined(SWD_BEST_OFF)
		if (s->use_best_off)
		{
			int i;
			for (i = 2; i < SWD_BEST_OFF; i++)
				if (s->best_pos[i] > 0)
					s->best_off[i] =
						swd_pos2off(s,s->best_pos[i]-1);

				else
					s->best_off[i] = 0;
		}
#endif
	}

	swd_remove_node(s,s->rp);

	/* add bp into HEAD2 */
	key = HEAD2(s->b,s->bp);
	s->head2[key] = (unsigned int)(s->bp);
}


/***********************************************************************
//
************************************************************************/

static int
init_match ( struct ucl_compress *c, struct ucl_swd *s,
	const uint8_t *dict, unsigned int dict_len,
	uint32_t flags )
{
	int r;
	
	assert(!c->init);
	c->init = 1;
	
	s->c = c;
	
	c->last_m_len = c->last_m_off = 0;
	
	c->textsize = c->codesize = c->printcount = 0;
	c->lit_bytes = c->match_bytes = c->rep_bytes = 0;
	c->lazy = 0;
	
	r = swd_init(s,dict,dict_len);
	if (r != UCL_E_OK)
	{
		swd_exit(s);
		return r;
	}
	
	s->use_best_off = (flags & 1) ? 1 : 0;
	return UCL_E_OK;
}

static int
find_match ( struct ucl_compress *c, struct ucl_swd *s,
	unsigned int this_len, unsigned int skip )
{
	assert(c->init);
	
	if (skip > 0)
	{
		assert(this_len >= skip);
		swd_accept(s, this_len - skip);
		c->textsize += this_len - skip + 1;
	}
	else
	{
		assert(this_len <= 1);
		c->textsize += this_len - skip;
	}
	
	s->m_len = THRESHOLD;
#ifdef SWD_BEST_OFF
	if (s->use_best_off)
		memset(s->best_pos,0,sizeof(s->best_pos));
#endif
	swd_findbest(s);
	c->m_len = s->m_len;
	c->m_off = s->m_off;
	
	swd_getbyte(s);
	
	if (s->b_char < 0)
	{
		c->look = 0;
		c->m_len = 0;
		swd_exit(s);
	}
	else
	{
		c->look = s->look + 1;
	}
	c->bp = c->ip - c->look;
	
#if 0
	/* brute force match search */
	if (c->m_len > THRESHOLD && c->m_len + 1 <= c->look)
	{
		const uint8_t *ip = c->bp;
		const uint8_t *m  = c->bp - c->m_off;
		const uint8_t *in = c->in;
		
		if (ip - in > N)
			in = ip - N;
		for (;;)
		{
			while (*in != *ip)
				in++;
			if (in == ip)
				break;
			if (in != m)
				if (memcmp(in,ip,c->m_len+1) == 0)
					printf("%p %p %p %5d\n",
						in, ip, m, c->m_len);

			in++;
		}
	}
#endif
	
	return UCL_E_OK;
}


static int bbConfig(struct ucl_compress *c, int endian, int bitsize)
{
	if (endian != -1)
	{
		if (endian != 0)
			return UCL_E_ERROR;
		c->bb_c_endian = endian;
	}
	if (bitsize != -1)
	{
		if (bitsize != 8 && bitsize != 16 && bitsize != 32)
			return UCL_E_ERROR;
		c->bb_c_s = bitsize;
		c->bb_c_s8 = bitsize / 8;
	}
	c->bb_b = 0; c->bb_k = 0;
	c->bb_p = NULL;
	c->bb_op = NULL;
	return UCL_E_OK;
}

static void bbWriteBits(struct ucl_compress *c)
{
	uint8_t *p = c->bb_p;
	uint32_t b = c->bb_b;

	p[0] = (uint8_t)(b >>  0);
	if (c->bb_c_s >= 16)
	{
		p[1] = (uint8_t)(b >>  8);
		if (c->bb_c_s == 32)
		{
			p[2] = (uint8_t)(b >> 16);
			p[3] = (uint8_t)(b >> 24);
		}
	}
}


static void bbPutBit(struct ucl_compress *c, unsigned bit)
{
	assert(bit == 0 || bit == 1);
	assert(c->bb_k <= c->bb_c_s);

	if (c->bb_k < c->bb_c_s)
	{
		if (c->bb_k == 0)
		{
			assert(c->bb_p == NULL);
			c->bb_p = c->bb_op;
			c->bb_op += c->bb_c_s8;
		}
		assert(c->bb_p != NULL);
		assert(c->bb_p + c->bb_c_s8 <= c->bb_op);

		c->bb_b = (c->bb_b << 1) + bit;
		c->bb_k++;
	}
	else
	{
		assert(c->bb_p != NULL);
		assert(c->bb_p + c->bb_c_s8 <= c->bb_op);

		bbWriteBits(c);
		c->bb_p = c->bb_op;
		c->bb_op += c->bb_c_s8;
		c->bb_b = bit;
		c->bb_k = 1;
	}
}


static void bbPutByte(struct ucl_compress *c, unsigned b)
{
	/**printf("putbyte %p %p %x  (%d)\n", op, bb_p, x, bb_k);*/
	assert(c->bb_p == NULL || c->bb_p + c->bb_c_s8 <= c->bb_op);
	*c->bb_op++ = (uint8_t)(b);
}

static void bbFlushBits(struct ucl_compress *c, unsigned filler_bit)
{
	if (c->bb_k > 0)
	{
		assert(c->bb_k <= c->bb_c_s);
		while (c->bb_k != c->bb_c_s)
			bbPutBit(c, filler_bit);
		bbWriteBits(c);
		c->bb_k = 0;
	}
	c->bb_p = NULL;
}



/***********************************************************************
//
************************************************************************/


static void code_prefix_ss11(struct ucl_compress *c, uint32_t i)
{
	if (i >= 2)
	{
		uint32_t t = 4;
		i += 2;
		do {
			t <<= 1;
		} while (i >= t);
		t >>= 1;
		do {
			t >>= 1;
			bbPutBit(c, (i & t) ? 1 : 0);
			bbPutBit(c, 0);
		} while (t > 2);
	}
	bbPutBit(c, (unsigned)i & 1);
	bbPutBit(c, 1);
}

static void
code_match(struct ucl_compress *c, unsigned int m_len, const unsigned int m_off)

{
	while (m_len > c->conf.max_match)
	{
		code_match(c, c->conf.max_match - 3, m_off);
		m_len -= c->conf.max_match - 3;
	}
	
	c->match_bytes += m_len;
	if (m_len > c->result[3])
		c->result[3] = m_len;
	if (m_off > c->result[1])
		c->result[1] = m_off;

	bbPutBit(c, 0);

	if (m_off == c->last_m_off)
	{
		bbPutBit(c, 0);
		bbPutBit(c, 1);
	}
	else
	{
		code_prefix_ss11(c, 1 + ((m_off - 1) >> 8));
		bbPutByte(c, (unsigned)m_off - 1);
	}
	m_len = m_len - 1 - (m_off > M2_MAX_OFFSET);
	if (m_len >= 4)
	{
		bbPutBit(c,0);
		bbPutBit(c,0);
		code_prefix_ss11(c, m_len - 4);
	}
	else
	{
		bbPutBit(c, m_len > 1);
		bbPutBit(c, (unsigned)m_len & 1);
	}

	c->last_m_off = m_off;
}

static void
code_run(struct ucl_compress *c, const uint8_t *ii, unsigned int lit)
{
	if (lit == 0)
		return;
	c->lit_bytes += lit;
	if (lit > c->result[5])
		c->result[5] = lit;
	do {
		bbPutBit(c, 1);
		bbPutByte(c, *ii++);
	} while (--lit > 0);
}

/***********************************************************************
//
************************************************************************/

static int
len_of_coded_match(struct ucl_compress *c, unsigned int m_len, unsigned int
	m_off)

{
	int b;
	if (m_len < 2 || (m_len == 2 && (m_off > M2_MAX_OFFSET))
		|| m_off > c->conf.max_offset)
		return -1;
	assert(m_off > 0);
	
	m_len = m_len - 2 - (m_off > M2_MAX_OFFSET);
	
	if (m_off == c->last_m_off)
		b = 1 + 2;
	else
	{
		b = 1 + 10;
		m_off = (m_off - 1) >> 8;
		while (m_off > 0)
		{
			b += 2;
			m_off >>= 1;
		}
	}

	b += 2;
	if (m_len < 3)
		return b;
	m_len -= 3;

	do {
		b += 2;
		m_len >>= 1;
	} while (m_len > 0);

	return b;
}

int ucl_nrv2b_99_compress(
	const uint8_t *in, unsigned long in_len,
	uint8_t *out, unsigned long *out_len,
	unsigned int *result)
{
	const uint8_t *ii;
	unsigned int lit;
	unsigned int m_len, m_off;
	struct ucl_compress c_buffer;
	struct ucl_compress * const c = &c_buffer;
	struct ucl_swd *swd;
	unsigned int result_buffer[16];
	int r;

/* max compression */
#define SC_TRY_LAZY    2
#define SC_GOOD_LENGTH F
#define SC_MAX_LAZY    F
#define SC_NICE_LENGTH F
#define SC_MAX_CHAIN   4096
#define SC_FLAGS       1
#define SC_MAX_OFFSET  N
	
	memset(c, 0, sizeof(*c));
	c->ip = c->in = in;
	c->in_end = in + in_len;
	c->out = out;
	c->result = result ? result : result_buffer;
	memset(c->result, 0, 16*sizeof(*c->result));
	c->result[0] = c->result[2] = c->result[4] = UINT_MAX;
	result = NULL;
	memset(&c->conf, 0xff, sizeof(c->conf));
	r = bbConfig(c, ENDIAN, BITSIZE);
	if (r == 0)
		r = bbConfig(c, c->conf.bb_endian, c->conf.bb_size);
	if (r != 0)
		return UCL_E_INVALID_ARGUMENT;
	c->bb_op = out;
	
	ii = c->ip;             /* point to start of literal run */
	lit = 0;
	

	swd = (struct ucl_swd *) malloc(sizeof(*swd));
	if (!swd)
		return UCL_E_OUT_OF_MEMORY;

	swd->f = F;
	swd->n = N;
	if (in_len >= 256 && in_len < swd->n)
		swd->n = in_len;
	if (swd->f < 8 || swd->n < 256)
		return UCL_E_INVALID_ARGUMENT;

	r = init_match(c,swd,NULL,0, SC_FLAGS);
	if (r != UCL_E_OK)
	{
		free(swd);
		return r;
	}
	if (SC_MAX_CHAIN > 0)
		swd->max_chain = SC_MAX_CHAIN;
	if (SC_NICE_LENGTH > 0)
		swd->nice_length = SC_NICE_LENGTH;
	if (c->conf.max_match < swd->nice_length)
		swd->nice_length = c->conf.max_match;
	
	c->last_m_off = 1;
	r = find_match(c,swd,0,0);
	if (r != UCL_E_OK)
		return r;
	while (c->look > 0)
	{
		unsigned int ahead;
		unsigned int max_ahead;
		int l1, l2;
		
		c->codesize = c->bb_op - out;
		
		m_len = c->m_len;
		m_off = c->m_off;
		
		assert(c->bp == c->ip - c->look);
		assert(c->bp >= in);
		if (lit == 0)
			ii = c->bp;
		assert(ii + lit == c->bp);
		assert(swd->b_char == *(c->bp));
		
		if (m_len < 2 || (m_len == 2 && (m_off > M2_MAX_OFFSET))
			|| m_off > c->conf.max_offset)
		{
			/* a literal */
			lit++;
			swd->max_chain = SC_MAX_CHAIN;
			r = find_match(c,swd,1,0);
			assert(r == 0);
			continue;
		}
		
		/* a match */
		assert_match(swd,m_len,m_off);
		
		/* shall we try a lazy match ? */
		ahead = 0;
		if (SC_TRY_LAZY <= 0 || m_len >= SC_MAX_LAZY || m_off ==
			c->last_m_off)

		{
			/* no */
			l1 = 0;
			max_ahead = 0;
		}
		else
		{
			/* yes, try a lazy match */
			l1 = len_of_coded_match(c,m_len,m_off);
			assert(l1 > 0);
			max_ahead = SC_TRY_LAZY;
			if ((m_len - 1) < max_ahead) {
				max_ahead = m_len -1;
			}
		}
		
		while (ahead < max_ahead && c->look > m_len)
		{
			if (m_len >= SC_GOOD_LENGTH)
				swd->max_chain = SC_MAX_CHAIN >> 2;
			else
				swd->max_chain = SC_MAX_CHAIN;
			r = find_match(c,swd,1,0);
			ahead++;
			
			assert(r == 0);
			assert(c->look > 0);
			assert(ii + lit + ahead == c->bp);
			
			if (c->m_len < 2)
				continue;
			l2 = len_of_coded_match(c,c->m_len,c->m_off);
			if (l2 < 0)
				continue;
			if (l1 + (int)(ahead + c->m_len - m_len) * 5 > l2 +
				(int)(ahead) * 9)
			{
				c->lazy++;
				assert_match(swd,c->m_len,c->m_off);
				lit += ahead;
				assert(ii + lit == c->bp);
				goto lazy_match_done;
			}
		}
		
		assert(ii + lit + ahead == c->bp);
		
		/* 1 - code run */
		code_run(c,ii,lit);
		lit = 0;
		
		/* 2 - code match */
		code_match(c,m_len,m_off);
		swd->max_chain = SC_MAX_CHAIN;
		r = find_match(c,swd,m_len,1+ahead);
		assert(r == 0);
		
	lazy_match_done: ;
	}
	
	/* store final run */
	code_run(c,ii,lit);
	
	/* EOF */
	bbPutBit(c, 0);
	code_prefix_ss11(c, 0x1000000U);
	bbPutByte(c, 0xff);

	bbFlushBits(c, 0);
	
	assert(c->textsize == in_len);
	c->codesize = c->bb_op - out;
	*out_len = c->bb_op - out;
	
#if 0
	printf("%7ld %7ld -> %7ld   %7ld %7ld   %ld  (max: %d %d %d)\n",
		(long) c->textsize, (long) in_len, (long) c->codesize,
		c->match_bytes, c->lit_bytes,  c->lazy,
		c->result[1], c->result[3], c->result[5]);
#endif
	assert(c->lit_bytes + c->match_bytes == in_len);
	
	swd_exit(swd);
	free(swd);

	return UCL_E_OK;
}


void Encode(void)  /* compression */
{
	uint8_t *in, *out;
	unsigned long in_len, out_len;
	uint32_t tw;
	int r;
	fseek(infile, 0, SEEK_END);
	in_len = ftell(infile);
#ifdef VERBOSE
	if ((signed long)in_len < 0)
		Fprintf((stderr, "Errno: %d", errno));
#endif
#if UCLPACK_COMPAT
	{
		uint8_t byte;
		if (fwrite(magic, sizeof(magic), 1, outfile) != 1)
			Error("Can't write.");
		tw = htonl(0); /* flags */
		if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
			Error("Can't write.");
		byte = 0x2b;		/* method */
		if (fwrite(&byte, sizeof(byte), 1, outfile) != 1)
			Error("Can't write.");
		byte = 10;		/* level */
		if (fwrite(&byte, sizeof(byte), 1, outfile) != 1)
			Error("Can't write.");
		tw = htonl(256*1024);		/* block_size */
		if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
			Error("Can't write.");
		tw = htonl(in_len);
		if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
			Error("Can't write.");	/* output size of text */
	}
#else
	tw = host_to_i86ul(in_len);
	if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
		Error("Can't write.");	/* output size of text */
#endif	
	if (in_len == 0)
		return;
	rewind(infile);

	in = malloc(in_len);
	out_len = in_len + (in_len/8) + 256;
	out = malloc(out_len);
	if (!in || !out) {
		Error("Can't malloc");
	}
	if (fread(in, in_len, 1, infile) != 1) {
		Error("Can't read");
	}
	r = ucl_nrv2b_99_compress(in, in_len, out, &out_len, 0 );
#if UCLPACK_COMPAT
	tw = htonl(out_len);
	if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
		Error("Can't write.");	/* file size of text */

#endif
	if (fwrite(out, out_len, 1, outfile) != 1) {
		Error("Write error\n");
	}
#if UCLPACK_COMPAT
	tw = htonl(0); /* EOF marker */
	if (fwrite(&tw, sizeof(tw), 1, outfile) != 1)
		Error("Can't write.");

#endif

#ifdef	LONG_REPORT
	Fprintf((stderr, "input size    %ld bytes\n", in_len));
	Fprintf((stderr, "output size   %ld bytes\n", out_len));
	Fprintf((stderr, "input/output  %.3f\n", (double)in_len / out_len));
#else
	Fprintf((stderr, "input/output = %ld/%ld = %.3f\n", in_len, out_len,
		(double)in_len / out_len));
#endif
	
}

#endif

#ifdef DECODE

#define GETBIT_8(bb, src, ilen) \
    (((bb = bb & 0x7f ? bb*2 : ((unsigned)src[ilen++]*2+1)) >> 8) & 1)

#define GETBIT_LE16(bb, src, ilen) \
    (bb*=2,bb&0xffff ? (bb>>16)&1 : (ilen+=2,((bb=(src[ilen-2]+src[ilen-1]*256u)*2+1)>>16)&1))

#define GETBIT_LE32(bb, src, ilen) \
    (bc > 0 ? ((bb>>--bc)&1) : (bc=31,\
    bb=*(const uint32_t *)((src)+ilen),ilen+=4,(bb>>31)&1))

#if ENDIAN == 0 && BITSIZE == 8
#define GETBIT(bb, src, ilen) GETBIT_8(bb, src, ilen)
#endif
#if ENDIAN == 0 && BITSIZE == 16
#define GETBIT(bb, src, ilen) GETBIT_LE16(bb, src, ilen)
#endif
#if ENDIAN == 0 && BITSIZE == 32
#define GETBIT(bb, src, ilen) GETBIT_LE32(bb, src, ilen)
#endif

#ifndef GETBIT
#error "Bad Combination of ENDIAN and BITSIZE values specified"
#endif

#undef SAFE

#ifdef SAFE
#define FAIL(x,r)   if (x) { Error(r); }
#else
#define FAIL(x,r)
#endif

void Decode(void)  /* recover */
{
	uint32_t tw;
	uint8_t *src, *dst;
	unsigned long max_src_len, src_len, dst_len;
	unsigned long ilen = 0, olen = 0, last_m_off =  1;
	uint32_t bb = 0;
	unsigned bc = 0;
#if UCLPACK_COMPAT
	if (fseek(infile, sizeof(magic) + sizeof(tw) + 1 + 1 + sizeof(tw),
		SEEK_SET) != 0)

		Error("Seek Error");
	if (fread(&tw, sizeof(tw), 1, infile) < 1)
		Error("Can't read"); /* read size of text */
	dst_len = ntohl(tw);
	if (fread(&tw, sizeof(tw), 1, infile) < 1)
		Error("Can't read"); /* read size of file */
	max_src_len = ntohl(tw);
#else
	if (fread(&tw, sizeof(tw), 1, infile) < 1)
		Error("Can't read"); /* read size of text */
	dst_len = i86ul_to_host(tw);
	max_src_len = dst_len + (dst_len/8) + 256;
#endif
	if (dst_len == 0)
		return;
	dst = malloc(dst_len);
	if (!dst)
		Error("Can't malloc");
	src = malloc(max_src_len);
	if (!src)
		Error("Can't malloc");
	src_len = fread(src, 1, max_src_len, infile);
	if (src_len <= 0) 
		Error("Can't read");

	for(;;) {
		unsigned int m_off, m_len;
		while(GETBIT(bb, src, ilen)) {
			FAIL(ilen >= src_len, "input overrun");
			FAIL(olen >= dst_len, "output  overrun");
			dst[olen++] = src[ilen++];
		}
		m_off = 1;
		do {
			m_off = m_off*2 + GETBIT(bb, src, ilen);
			FAIL(ilen >= src_len, "input overrun");
			FAIL(m_off > 0xffffffU +3, "lookbehind overrun");
		} while (!GETBIT(bb, src, ilen));
		if (m_off == 2)
		{
			m_off = last_m_off;
		}
		else
		{
			FAIL(ilen >= src_len, "input overrun");
			m_off = (m_off - 3)*256 + src[ilen++];
			if(m_off == 0xffffffffU)
				break;
			last_m_off = ++m_off;
		}
		m_len = GETBIT(bb, src, ilen);
		m_len = m_len*2 + GETBIT(bb, src, ilen);
		if (m_len == 0) 
		{
			m_len++;
			do {
				m_len = m_len*2 + GETBIT(bb, src, ilen);
				FAIL(ilen >= src_len, "input overrun");
				FAIL(m_len >= dst_len, "output overrun");
			} while(!GETBIT(bb, src, ilen));
			m_len += 2;
		}
		m_len += (m_off > 0xd00);
		FAIL(olen + m_len > dst_len, "output overrun");
		FAIL(m_off > olen, "lookbeind overrun");
		{
			const uint8_t *m_pos;
			m_pos = dst + olen - m_off;
			dst[olen++] = *m_pos++;
			do {
				dst[olen++] = *m_pos++;
			} while(--m_len > 0);
		}
	}
	FAIL(ilen < src_len, "input not consumed");
	FAIL(ilen > src_len, "input overrun");
	assert(ilen == src_len);
	Fprintf((stderr, "%12ld\n", olen));
	if (dst_len != olen) {
		fprintf(stderr, "length != expected length\n");
	}
	if (fwrite(dst, olen, 1, outfile) != 1)
		Error("Write error\n");
	free(src);
	free(dst);
}
#endif

#ifdef MAIN
int main(int argc, char *argv[])
{
	char  *s;
	FILE  *f;
	int    c;
	
	if (argc == 2) {
		outfile = stdout;
		if ((f = tmpfile()) == NULL) {
			perror("tmpfile");
			return EXIT_FAILURE;
		}
		while ((c = getchar()) != EOF)
			fputc(c, f);
		rewind(infile = f);
	}
	else if (argc != 4) {
		Fprintf((stderr, "'nrv2b e file1 file2' encodes file1 into file2.\n"
			"'nrv2b d file2 file1' decodes file2 into file1.\n"));

		return EXIT_FAILURE;
	}
	if (argc == 4) {
		if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
			|| (s = argv[2], (infile  = fopen(s, "rb")) == NULL)
			|| (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
			Fprintf((stderr, "??? %s\n", s));
			return EXIT_FAILURE;
		}
	}
	if (toupper(*argv[1]) == 'E')
		Encode();
	else
		Decode();
	fclose(infile);
	fclose(outfile);
	return EXIT_SUCCESS;
}
#endif