File: quantize.c

package info (click to toggle)
xslideshow 3.1-7
  • links: PTS
  • area: non-free
  • in suites: sarge
  • size: 792 kB
  • ctags: 1,375
  • sloc: ansic: 14,006; makefile: 897; sh: 1
file content (1467 lines) | stat: -rw-r--r-- 45,171 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
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
#include "xslideshow.h"

#if defined(__STDC__) || defined(__cplusplus)
# define P_(s) s
#else
# define P_(s) ()
#endif

extern void myevent P_(());
extern void goodbyekiss P_(());

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																				%
%																				%
%																				%
%	QQQ    U   U    AAA    N    N  TTTTT  IIIII  ZZZZZ  EEEEE					%
%  Q   Q   U   U    A A    NN   N    T      I      ZZ   E						%
%  Q   Q   U   U   AAAAA   N N  N    T      I     ZZZ   EEEEE					%
%  Q   QQ  U   U   A   A   N   NN    T      I    ZZ     E						%
%	QQQQ    UUU   A     A  N    N    T    IIIII ZZZZZ   EEEEE					%
%										 										%
%										 										%
%			Reduce the Number of Unique Colors in an Image		 				%
%										 										%
%										 										%
%										 										%
%				 Software Design					 							%
%				 John Cristy					 								%
%					July 1992													%
%										 										%
%	Copyright 1993 E. I. du Pont de Nemours & Company							%
%										 										%
%	Permission to use, copy, modify, distribute, and sell this software and		%
%	its documentation for any purpose is hereby granted without fee,		 	%
%	provided that the above Copyright notice appear in all copies and that	 	%
%	both that Copyright notice and this permission notice appear in				%
%	supporting documentation, and that the name of E. I. du Pont de Nemours		%
%	& Company not be used in advertising or publicity pertaining to				%
%	distribution of the software without specific, written prior			 	%
%	permission.	E. I. du Pont de Nemours & Company makes no representations	 	%
%	about the suitability of this software for any purpose.	It is provided		%
%	"as is" without express or implied warranty.					 			%
%										 										%
%	E. I. du Pont de Nemours & Company disclaims all warranties with regard		%
%	to this software, including all implied warranties of merchantability		%
%	and fitness, in no event shall E. I. du Pont de Nemours & Company be		%
%	liable for any special, indirect or consequential damages or any		 	%
%	damages whatsoever resulting from loss of use, data or profits, whether		%
%	in an action of contract, negligence or other tortious action, arising	 	%
%	out of or in connection with the use or performance of this software.		%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Realism in computer graphics typically requires using 24 bits/pixel to
%	generate an image.	Yet many graphic display devices do not contain
%	the amount of memory necessary to match the spatial and color
%	resolution of the human eye.	The QUANTIZE program takes a 24 bit
%	image and reduces the number of colors so it can be displayed on
%	raster device with less bits per pixel.	In most instances, the
%	quantized image closely resembles the original reference image.
%
%	A reduction of colors in an image is also desirable for image
%	transmission and real-time animation.
%
%	Function Quantize takes a standard RGB or monochrome images and quantizes
%	them down to some fixed number of colors.
%
%	For purposes of color allocation, an image is a set of n pixels, where
%	each pixel is a point in RGB space.	RGB space is a 3-dimensional
%	vector space, and each pixel, pi,	is defined by an ordered triple of
%	red, green, and blue coordinates, (ri, gi, bi).
%
%	Each primary color component (red, green, or blue) represents an
%	intensity which varies linearly from 0 to a maximum value, cmax, which
%	corresponds to full saturation of that color.	Color allocation is
%	defined over a domain consisting of the cube in RGB space with
%	opposite vertices at (0,0,0) and (cmax,cmax,cmax).	QUANTIZE requires
%	cmax = 255.
%
%	The algorithm maps this domain onto a tree in which each node
%	represents a cube within that domain.	In the following discussion
%	these cubes are defined by the coordinate of two opposite vertices:
%	The vertex nearest the origin in RGB space and the vertex farthest
%	from the origin.
%
%	The tree's root node represents the the entire domain, (0,0,0) through
%	(cmax,cmax,cmax).	Each lower level in the tree is generated by
%	subdividing one node's cube into eight smaller cubes of equal size.
%	This corresponds to bisecting the parent cube with planes passing
%	through the midpoints of each edge.
%
%	The basic algorithm operates in three phases: Classification,
%	Reduction, and Assignment.	Classification builds a color
%	description tree for the image.	Reduction collapses the tree until
%	the number it represents, at most, the number of colors desired in the
%	output image.	Assignment defines the output image's color map and
%	sets each pixel's color by reclassification in the reduced tree.
%
%	Classification begins by initializing a color description tree of
%	sufficient depth to represent each possible input color in a leaf.
%	However, it is impractical to generate a fully-formed color
%	description tree in the classification phase for realistic values of
%	cmax.	If colors components in the input image are quantized to k-bit
%	precision, so that cmax= 2k-1, the tree would need k levels below the
%	root node to allow representing each possible input color in a leaf.
%	This becomes prohibitive because the tree's total number of nodes is
%	1 + sum(i=1,k,8k).
%
%	A complete tree would require 19,173,961 nodes for k = 8, cmax = 255.
%	Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
%	Initializes data structures for nodes only as they are needed;	(2)
%	Chooses a maximum depth for the tree as a function of the desired
%	number of colors in the output image (currently log2(colormap size)).
%
%	For each pixel in the input image, classification scans downward from
%	the root of the color description tree.	At each level of the tree it
%	identifies the single node which represents a cube in RGB space
%	containing the pixel's color.	It updates the following data for each
%	such node:
%
%	n1 : Number of pixels whose color is contained in the RGB cube
%	which this node represents;
%
%	n2 : Number of pixels whose color is not represented in a node at
%	lower depth in the tree;	initially,	n2 = 0 for all nodes except
%	leaves of the tree.
%
%	Sr, Sg, Sb : Sums of the red, green, and blue component values for
%	all pixels not classified at a lower depth. The combination of
%	these sums and n2	will ultimately characterize the mean color of a
%	set of pixels represented by this node.
%
%	Reduction repeatedly prunes the tree until the number of nodes with
%	n2 > 0 is less than or equal to the maximum number of colors allowed
%	in the output image.	On any given iteration over the tree, it selects
%	those nodes whose n1	count is minimal for pruning and merges their
%	color statistics upward. It uses a pruning threshold, ns, to govern
%	node selection as follows:
%
%	ns = 0
%	while number of nodes with (n2 > 0) > required maximum number of colors
%		prune all nodes such that n1 <= ns
%		Set ns to minimum n1 in remaining nodes
%
%	When a node to be pruned has offspring, the pruning procedure invokes
%	itself recursively in order to prune the tree from the leaves upward.
%	n2,	Sr, Sg,	and	Sb in a node being pruned are always added to the
%	corresponding data in that node's parent.	This retains the pruned
%	node's color characteristics for later averaging.
%
%	For each node, n2 pixels exist for which that node represents the
%	smallest volume in RGB space containing those pixel's colors.	When n2
%	> 0 the node will uniquely define a color in the output image. At the
%	beginning of reduction,	n2 = 0	for all nodes except a the leaves of
%	the tree which represent colors present in the input image.
%
%	The other pixel count, n1, indicates the total number of colors
%	within the cubic volume which the node represents.	This includes n1 -
%	n2	pixels whose colors should be defined by nodes at a lower level in
%	the tree.
%
%	Assignment generates the output image from the pruned tree.	The
%	output image consists of two parts: (1)	A color map, which is an
%	array of color descriptions (RGB triples) for each color present in
%	the output image;	(2)	A pixel array, which represents each pixel as
%	an index into the color map array.
%
%	First, the assignment phase makes one pass over the pruned color
%	description tree to establish the image's color map.	For each node
%	with n2	> 0, it divides Sr, Sg, and Sb by n2 .	This produces the
%	mean color of all pixels that classify no lower than this node.	Each
%	of these colors becomes an entry in the color map.
%
%	Finally,	the assignment phase reclassifies each pixel in the pruned
%	tree to identify the deepest node containing the pixel's color.	The
%	pixel's value in the pixel array becomes the index of this node's mean
%	color in the color map.
%
%	For efficiency, QUANTIZE requires that the reference image be in a
%	run-length encoded format.
%
%	With the permission of USC Information Sciences Institute, 4676 Admiralty
%	Way, Marina del Rey, California	90292, this code was adapted from module
%	ALCOLS written by Paul Raveling.
%
%	The names of ISI and USC are not used in advertising or publicity
%	pertaining to distribution of the software without prior specific
%	written permission from ISI.
%
%
*/

#if defined(__STDC__) || defined(__cplusplus)
# define _Declare(s) s
#else
# define _Declare(s) ()
#endif

/*
	Image define declarations.
*/
#define Intensity(color)	(dword)	\
	((dword) ((color).red*77+(color).green*150+(color).blue*29) >> 8)
#define MaxColormapSize	65535
#define MaxRGB	255

/*
	Image structure declarations.
*/
typedef struct _ColorPacket
{
	byte red, green, blue;
	word index;
} ColorPacket;

/*
	Image colorspaces:
*/
#define RGBColorspace	1
#define GRAYColorspace 2

typedef struct _ImageMagick
{
	dword packets, columns, rows, colors;
	ColorPacket *colormap, *pixels;
} ImageMagick;

/*
	Define declarations.
*/
#define color_number	number_colors
#define MaxNodes		266817
#define MaxTreeDepth	8	/* Log2(MaxRGB) */
#define NodesInAList	2048

/*
	Structures.
*/
typedef struct _Node
{
	struct _Node *parent, *child[8];
	byte id, level, children, mid_red, mid_green, mid_blue;
	dword number_colors, number_unique, total_red, total_green, total_blue;
} Node;

typedef struct _Nodes
{
	Node nodes[NodesInAList];
	struct _Nodes *next;
} Nodes;

typedef struct _Cube
{
	Node *root;
	ColorPacket color, *colormap;
	dword depth, colors, pruning_threshold, next_pruning_threshold, distance;
	dword shift[MaxTreeDepth+1], squares[MaxRGB+MaxRGB+1];
	dword nodes, free_nodes, color_number;
	Node *next_node;
	Nodes *node_queue;
} Cube;

/*
	Global variables.
*/
static Cube cube;

/*
	Forward declarations.
*/
static Node *InitializeNode _Declare((dword,dword,Node *, dword, dword,dword));
static dword DitherImage _Declare((ImageMagick *));
static void ClosestColor _Declare((Node *));
static void ColormapMagick _Declare((Node *));
static void PruneLevel _Declare((Node *));

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																			 	%
%										 										%
%										 										%
%	A s s i g n m e n t															%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure Assignment generates the output image from the pruned tree.	The
%	output image consists of two parts: (1)	A color map, which is an
%	array of color descriptions (RGB triples) for each color present in
%	the output image;	(2)	A pixel array, which represents each pixel as
%	an index into the color map array.
%
%	First, the assignment phase makes one pass over the pruned color
%	description tree to establish the image's color map.	For each node
%	with n2	> 0, it divides Sr, Sg, and Sb by n2 .	This produces the
%	mean color of all pixels that classify no lower than this node.	Each
%	of these colors becomes an entry in the color map.
%
%	Finally,	the assignment phase reclassifies each pixel in the pruned
%	tree to identify the deepest node containing the pixel's color.	The
%	pixel's value in the pixel array becomes the index of this node's mean
%	color in the color map.
%
%	The format of the Assignment routine is:
%
%		Assignment(image,dither,colorspace,optimal)
%
%	A description of each parameter follows.
%
%	o image: Specifies a pointer to an Image structure;	returned from
%		ReadImage.
%
%	o dither: Set this integer value to something other than zero to
%		dither the quantized image.	The basic strategy of dithering is to
%		trade intensity resolution for spatial resolution by averaging the
%		intensities of several neighboring pixels.	Images which suffer
%		from severe contouring when quantized can be improved with the
%		technique of dithering.	Severe contouring generally occurs when
%		quantizing to very few colors, or to a poorly-chosen colormap.
%		Note, dithering is a computationally expensive process and will
%		increase processing time significantly.
%
%	o colorspace: An dwordeger value that indicates the colorspace.
%
%	o optimal: An dwordeger value greater than zero indicates that
%		the optimal representation of the reference image should be returned.
%
%
*/
static void Assignment(image,dither,colorspace,optimal)
ImageMagick *image;
dword dither, colorspace, optimal;
{
	int i;
	Node *node;
	ColorPacket *p;
	dword id;

	/*
	Allocate image colormap.
	*/
	image->colormap=(ColorPacket *)XtMalloc((dword) cube.colors*sizeof(ColorPacket));
	if (image->colormap == (ColorPacket *) NULL)
	{
		fprintf(stderr, "xslideshow: quantize() unable to quantize image, memory allocation failed\n");
		goodbyekiss();
	}
	cube.colormap=image->colormap;
	cube.colors=0;
	ColormapMagick(cube.root);
	image->colors=(dword) cube.colors;
	if ((image->colors == 2)	&& (colorspace == GRAYColorspace))
	{
		dword
		polarity;

		/*
		Monochrome image.
		*/
		polarity=Intensity(image->colormap[0]) > Intensity(image->colormap[1]);
		image->colormap[polarity].red=0;
		image->colormap[polarity].green=0;
		image->colormap[polarity].blue=0;
		image->colormap[!polarity].red=MaxRGB;
		image->colormap[!polarity].green=MaxRGB;
		image->colormap[!polarity].blue=MaxRGB;
	}
	/*
	Create a reduced color image.	For the non-optimal case we trade
	accuracy for speed improvements.
	*/
	if (dither)
		dither=!DitherImage(image);
	p=image->pixels;
	if (!dither)
		if (!optimal)
			for (i=0; i < (int)image->packets; i++)
			{
			/*
			Identify the deepest node containing the pixel's color.
			*/
			node=cube.root;
				for ( ; ; )
				{
					id=(p->red > node->mid_red ? 1 : 0) |
					(p->green > node->mid_green ? 1 : 0) << 1 |
					(p->blue > node->mid_blue ? 1 : 0) << 2;
					if ((node->children & (1 << id)) == 0)
						break;
					node=node->child[id];
				}
			p->index=(word) node->color_number;
			p++;

			myevent();
			}
		else
			for (i=0; i < (int)image->packets; i++)
			{
			/*
			Identify the deepest node containing the pixel's color.
			*/
				node=cube.root;
				for ( ; ; )
				{
					id=(p->red > node->mid_red ? 1 : 0) |
					(p->green > node->mid_green ? 1 : 0) << 1 |
					(p->blue > node->mid_blue ? 1 : 0) << 2;
					if ((node->children & (1 << id)) == 0)
					break;
					node=node->child[id];
				}
				/*
				Find closest color among siblings and their children.
				*/
				cube.color.red=p->red;
				cube.color.green=p->green;
				cube.color.blue=p->blue;
				cube.distance=(dword) (~0);
				ClosestColor(node->parent);
				p->index=cube.color_number;
				p++;

				myevent();
			}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																				%
%																				%
%										 										%
%	C l a s s i f i c a t i o n													%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure Classification begins by initializing a color description tree
%	of sufficient depth to represent each possible input color in a leaf.
%	However, it is impractical to generate a fully-formed color
%	description tree in the classification phase for realistic values of
%	cmax.	If colors components in the input image are quantized to k-bit
%	precision, so that cmax= 2k-1, the tree would need k levels below the
%	root node to allow representing each possible input color in a leaf.
%	This becomes prohibitive because the tree's total number of nodes is
%	1 + sum(i=1,k,8k).
%
%	A complete tree would require 19,173,961 nodes for k = 8, cmax = 255.
%	Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
%	Initializes data structures for nodes only as they are needed;	(2)
%	Chooses a maximum depth for the tree as a function of the desired
%	number of colors in the output image (currently log2(colormap size)).
%
%	For each pixel in the input image, classification scans downward from
%	the root of the color description tree.	At each level of the tree it
%	identifies the single node which represents a cube in RGB space
%	containing It updates the following data for each such node:
%
%	n1 : Number of pixels whose color is contained in the RGB cube
%	which this node represents;
%
%	n2 : Number of pixels whose color is not represented in a node at
%	lower depth in the tree;	initially,	n2 = 0 for all nodes except
%	leaves of the tree.
%
%	Sr, Sg, Sb : Sums of the red, green, and blue component values for
%	all pixels not classified at a lower depth. The combination of
%	these sums and n2	will ultimately characterize the mean color of a
%	set of pixels represented by this node.
%
%	The format of the Classification routine is:
%
%		Classification(image)
%
%	A description of each parameter follows.
%
%	o image: Specifies a pointer to an Image structure;	returned from
%		ReadImage.
%
%
*/
static void Classification(image)
ImageMagick *image;
{
	int i;
	Node *node;
	ColorPacket *p;
	dword bisect, count, id, level;

	p=image->pixels;
	for (i=0; i < (int)image->packets; i++)
	{
		if (cube.nodes > MaxNodes)
		{
		/*
			Prune one level if the color tree is too large.
		*/
		PruneLevel(cube.root);
		cube.depth--;
		}
		/*
			Start at the root and descend the color cube tree.
		*/
		count=1;
		node=cube.root;
		for (level=1; level < cube.depth; level++)
		{
			id=(p->red > node->mid_red ? 1 : 0) |
					(p->green > node->mid_green ? 1 : 0) << 1 |
					(p->blue > node->mid_blue ? 1 : 0) << 2;
			if (node->child[id] == (Node *) NULL)
			{
				/*
				Set colors of new node to contain pixel.
				*/
				node->children |= 1 << id;
				bisect=(dword) (1 << (MaxTreeDepth-level)) >> 1;
				node->child[id]=InitializeNode(id,level,node,
				node->mid_red+(id & 1 ? bisect : -bisect),
				node->mid_green+(id & 2 ? bisect : -bisect),
				node->mid_blue+(id & 4 ? bisect : -bisect));
				if (node->child[id] == (Node *) NULL)
				{
					fprintf(stderr,"xslideshow: quantize() unable to quantize image, memory allocation failed\n");
					goodbyekiss();
				}
				if (level == (cube.depth-1))
				cube.colors++;
			}
			/*
			Record the number of colors represented by this node.	Shift by level
			in the color description tree.
			*/
			node=node->child[id];
			node->number_colors += count << cube.shift[level];
		}
		/*
			Increment unique color count and sum RGB values for this leaf for later
			derivation of the mean cube color.
		*/
		node->number_unique += count;
		node->total_red += p->red*count;
		node->total_green += p->green*count;
		node->total_blue += p->blue*count;
		p++;

		myevent();
	}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																				%
%																				%
%										 										%
%	C l o s e s t C o l o r														%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure ClosestColor traverses the color cube tree at a particular node
%	and determines which colormap entry best represents the input color.
%
%	The format of the ClosestColor routine is:
%
%		ClosestColor(node)
%
%	A description of each parameter follows.
%
%	o node: The address of a structure of type Node which points to a
%		node in the color cube tree that is to be pruned.
%
%
*/
static void ClosestColor(node)
Node *node;
{
	dword id;

	/*
	Traverse any children.
	*/
	if (node->children != 0)
		for (id=0; id < 8; id++)
			if (node->children & (1 << id))
				ClosestColor(node->child[id]);

	if (node->number_unique != 0)
	{
		ColorPacket
		*color;

		dword
		blue_distance,
		green_distance,
		red_distance;

		dword
		distance;

		/*
		Determine if this color is "closest".
		*/
		color=cube.colormap+node->color_number;
		red_distance=(int) color->red-(int) cube.color.red+MaxRGB;
		green_distance=(int) color->green-(int) cube.color.green+MaxRGB;
		blue_distance=(int) color->blue-(int) cube.color.blue+MaxRGB;
		distance=cube.squares[red_distance]+cube.squares[green_distance]+
				cube.squares[blue_distance];
		if (distance < cube.distance)
		{
			cube.distance=distance;
			cube.color_number=(word) node->color_number;
		}
	}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																			 	%
%										 										%
%										 										%
%	C o l o r m a p																%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure Colormap traverses the color cube tree and notes each colormap
%	entry.	A colormap entry is any node in the color cube tree where the
%	number of unique colors is not zero.
%
%	The format of the Colormap routine is:
%
%		ColormapMagick(node)
%
%	A description of each parameter follows.
%
%	o node: The address of a structure of type Node which points to a
%		node in the color cube tree that is to be pruned.
%
%
*/
static void ColormapMagick(node)
Node *node;
{
	dword id;

	/*
	Traverse any children.
	*/
	if (node->children != 0)
		for (id=0; id < 8; id++)
			if (node->children & (1 << id))
				ColormapMagick(node->child[id]);

	if (node->number_unique > 0)
	{
		/*
		Colormap entry is defined by the mean color in this cube.
		*/
		cube.colormap[cube.colors].red=(byte)
				((node->total_red+(node->number_unique >> 1))/node->number_unique);
		cube.colormap[cube.colors].green=(byte)
				((node->total_green+(node->number_unique >> 1))/node->number_unique);
		cube.colormap[cube.colors].blue=(byte)
				((node->total_blue+(node->number_unique >> 1))/node->number_unique);
		node->color_number=cube.colors++;
	}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																		 		%
%										 										%
%										 										%
%	D i t h e r I m a g e														%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure DitherImage uses the Floyd-Steinberg algorithm to dither the
%	image.	Refer to "An Adaptive Algorithm for Spatial GreySscale", Robert W.
%	Floyd and Louis Steinberg, Proceedings of the S.I.D., Volume 17(2), 1976.
%
%	First find the closest representation to the reference pixel color in the
%	colormap, the node pixel is assigned this color.	Next, the colormap color
%	is subtracted from the reference pixels color, this represents the
%	quantization error.	Various amounts of this error are added to the pixels
%	ahead and below the node pixel to correct for this error.	The error
%	proportions are:
%
%		P	 7/16
%		3/16	5/16	1/16
%
%	The error is distributed left-to-right for even scanlines and right-to-left
%	for odd scanlines.
%
%	The format of the DitherImage routine is:
%
%		DitherImage(image)
%
%	A description of each parameter follows.
%
%	o image: Specifies a pointer to an Image structure;	returned from
%		ReadImage.
%
%
*/
static dword DitherImage(image)
ImageMagick *image;
{
	typedef struct _ScaledColorPacket
	{
		int red, green, blue;
	} ScaledColorPacket;

	int *cache, odd_scanline;
	int blue_error, green_error, red_error, step;
	Node *node;
	ColorPacket *p, *q;
	ScaledColorPacket *cs, *ns;
	byte *range_limit;
	dword id;
	ScaledColorPacket *scanline;
	byte blue, green, *range_table, red;
	dword i, x, y;
	word index;

	/*
	Allocate the cache & scanline buffers to keep track of quantization error.
	*/
	cache=(int *)XtMalloc((1 << 18)*sizeof(int));
	if (cache == (int *) NULL)
	{
		fprintf(stderr,"xslideshow: quantize() unable to dither image, memory allocation failed\n");
		return(True);
	}

	range_table=(byte *)XtMalloc(3*(MaxRGB+1)*sizeof(byte));
	if (range_table == (byte *) NULL)
	{
		XtFree((char *)cache);
		fprintf(stderr,"xslideshow: quantize() unable to dither image, memory allocation failed\n");
		return(True);
	}

	scanline=(ScaledColorPacket *)XtMalloc(2*(image->columns+2)*sizeof(ScaledColorPacket));
	if (scanline == (ScaledColorPacket *) NULL)
	{
		XtFree((char *)cache);
		XtFree((char *)range_table);
		fprintf(stderr,"xslideshow: quantize() unable to dither image, memory allocation failed\n");
		return(True);
	}
	/*
	Initialize tables.
	*/
	for (i=0; i < (1 << 18); i++)
		cache[i]=(-1);
	for (i=0; i <= MaxRGB; i++)
	{
		range_table[i]=0;
		range_table[i+(MaxRGB+1)]=(byte) i;
		range_table[i+(MaxRGB+1)*2]=MaxRGB;
	}
	range_limit=range_table+(MaxRGB+1);
	/*
	Preload first scanline.
	*/
	p=image->pixels;
	cs=scanline+1;
	for (i=0; i < image->columns; i++)
	{
		cs->red=p->red;
		cs->green=p->green;
		cs->blue=p->blue;
		p++;
		cs++;
	}
	odd_scanline=False;
	for (y=0; y < image->rows; y++)
	{
		if (y < (image->rows-1))
		{
			/*
				Read another scanline.
			*/
			ns=scanline+1;
			if (!odd_scanline)
				ns += (image->columns+2);
			for (i=0; i < image->columns; i++)
			{
				ns->red=p->red;
				ns->green=p->green;
				ns->blue=p->blue;
				p++;
				ns++;
			}
		}
		if (!odd_scanline)
		{
			/*
				Distribute error left-to-right for even scanlines.
			*/
			q=image->pixels+image->columns*y;
			cs=scanline+1;
			ns=scanline+(image->columns+2)+1;
			step=1;
		}
		else
		{
			/*
				Distribute error right-to-left for odd scanlines.
			*/
			q=image->pixels+image->columns*y+(image->columns-1);
			cs=scanline+(image->columns+2)+(image->columns-1)+1;
			ns=scanline+(image->columns-1)+1;
			step=(-1);
		}

		for (x=0; x < image->columns; x++)
		{
			red=range_limit[cs->red];
			green=range_limit[cs->green];
			blue=range_limit[cs->blue];
			i=(red >> 2) << 12 | (green >> 2) << 6 | blue >> 2;
			if (cache[i] < 0)
			{
				/*
					Identify the deepest node containing the pixel's color.
				*/
				node=cube.root;
				for ( ; ; )
				{
					id=(red > node->mid_red ? 1 : 0) |
						(green > node->mid_green ? 1 : 0) << 1 |
						(blue > node->mid_blue ? 1 : 0) << 2;
					if ((node->children & (1 << id)) == 0)
						break;
					node=node->child[id];
				}
				/*
					Find closest color among siblings and their children.
				*/
				cube.color.red=red;
				cube.color.green=green;
				cube.color.blue=blue;
				cube.distance=(dword) (~0);
				ClosestColor(node->parent);
				cache[i]=cube.color_number;
			}
			index=(word) cache[i];
			red_error=(int) red-(int) cube.colormap[index].red;
			green_error=(int) green-(int) cube.colormap[index].green;
			blue_error=(int) blue-(int) cube.colormap[index].blue;
			q->index=index;
			q += step;
			/*
				Propagate the error in these proportions:
					Q	 7/16
					3/16	5/16	1/16
			*/
			cs += step;
			cs->red += (red_error-((red_error*9+8)/16));
			cs->green += (green_error-((green_error*9+8)/16));
			cs->blue += (blue_error-((blue_error*9+8)/16));
			ns -= step;
			ns->red += (red_error*3+8)/16;
			ns->green += (green_error*3+8)/16;
			ns->blue += (blue_error*3+8)/16;
			ns += step;
			ns->red += (red_error*5+8)/16;
			ns->green += (green_error*5+8)/16;
			ns->blue += (blue_error*5+8)/16;
			ns += step;
			ns->red += (red_error+8)/16;
			ns->green += (green_error+8)/16;
			ns->blue += (blue_error+8)/16;
		}
		odd_scanline = !odd_scanline;
	}
	/*
	Free up memory.
	*/
	(void) XtFree((char *) scanline);
	(void) XtFree((char *) range_table);
	(void) XtFree((char *) cache);
	return(False);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																			 	%
%										 										%
%										 										%
%	I n i t i a l i z e C u b e													%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function InitializeCube initialize the Cube data structure.
%
%	The format of the InitializeCube routine is:
%
%		InitializeCube(number_colors,tree_depth,number_pixels,optimal)
%
%	A description of each parameter follows.
%
%	o number_colors: This integer value indicates the maximum number of
%		colors in the quantized image or colormap.	Here we use this value
%		to determine the depth of the color description tree.
%
%	o tree_depth: Normally, this integer value is zero or one.	A zero or
%		one tells Quantize to choose a optimal tree depth of Log4(number_colors).
%		A tree of this depth generally allows the best representation of the
%		reference image with the least amount of memory and the fastest
%		computational speed.	In some cases, such as an image with low color
%		dispersion (a few number of colors), a value other than
%		Log4(number_colors) is required.	To expand the color tree completely,
%		use a value of 8.
%
%	o number_pixels: Specifies the number of individual pixels in the image.
%
%	o optimal: An dwordeger value greater than zero indicates that
%		the optimal representation of the reference image should be returned.
%
*/
static void InitializeCube(number_colors,tree_depth,number_pixels,optimal)
dword number_colors, tree_depth, number_pixels, optimal;
{
	int i;
	static int log4[6] = {4, 16, 64, 256, 1024, ~0};
	dword level, max_shift;

	/*
	Initialize tree to describe color cube.	Depth is: Log4(colormap size)+2;
	*/
	cube.node_queue=(Nodes *) NULL;
	cube.nodes=0;
	cube.free_nodes=0;
	if (tree_depth > 1)
		cube.depth=MIN(tree_depth,8);
	else
	{
		for (i=0; i < 6; i++)
			if ((int)number_colors <= log4[i])
				break;
		cube.depth=i+3;
		if (!optimal)
			cube.depth--;
	}
	/*
	Initialize the shift values.
	*/
	for (max_shift=0; number_pixels != 0; max_shift++)
		number_pixels<<=1;
	for (level=0; level < cube.depth; level++)
	{
		cube.shift[level]=(cube.depth-level-1) << 1;
		if (cube.shift[level] > max_shift)
			cube.shift[level]=max_shift;
	}
	/*
	Initialize the square values.
	*/
	for (i=(-MaxRGB); i <= MaxRGB; i++)
		cube.squares[i+MaxRGB]=i*i;
	/*
	Initialize root node.
	*/
	cube.root=InitializeNode(0,0,(Node *) NULL,(MaxRGB+1) >> 1,(MaxRGB+1) >> 1,
	(MaxRGB+1) >> 1);
	if (cube.root == (Node *) NULL)
	{
		fprintf(stderr,"xslideshow: quantize() unable to quantize image, memory allocation failed\n");
		goodbyekiss();
	}
	cube.root->parent=cube.root;
	cube.root->number_colors=(dword) (~0);
	cube.colors=0;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%																	 			%
%										 										%
%										 										%
%	I n i t i a l i z e N o d e													%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function InitializeNode allocates memory for a new node in the color cube
%	tree and presets all fields to zero.
%
%	The format of the InitializeNode routine is:
%
%		node=InitializeNode(node,id,level,mid_red,mid_green,mid_blue)
%
%	A description of each parameter follows.
%
%	o node: The InitializeNode routine returns this integer address.
%
%	o id: Specifies the child number of the node.
%
%	o level: Specifies the level in the classification the node resides.
%
%	o mid_red: Specifies the mid point of the red axis for this node.
%
%	o mid_green: Specifies the mid point of the green axis for this node.
%
%	o mid_blue: Specifies the mid point of the blue axis for this node.
%
%
*/
static Node *InitializeNode(id,level,parent,mid_red,mid_green,mid_blue)
dword id, level;
Node *parent;
dword mid_red, mid_green, mid_blue;
{
	int i;
	Node *node;

	if (cube.free_nodes == 0)
	{
		Nodes
		*nodes;

		/*
		Allocate a new nodes of nodes.
		*/
		nodes=(Nodes *)XtMalloc(sizeof(Nodes));
		if (nodes == (Nodes *) NULL)
			return((Node *) NULL);
		nodes->next=cube.node_queue;
		cube.node_queue=nodes;
		cube.next_node=nodes->nodes;
		cube.free_nodes=NodesInAList;
	}
	cube.nodes++;
	cube.free_nodes--;
	node=cube.next_node++;
	node->parent=parent;
	for (i=0; i < 8; i++)
		node->child[i]=(Node *) NULL;
	node->id=id;
	node->level=level;
	node->children=0;
	node->mid_red=mid_red;
	node->mid_green=mid_green;
	node->mid_blue=mid_blue;
	node->number_colors=0;
	node->number_unique=0;
	node->total_red=0;
	node->total_green=0;
	node->total_blue=0;
	return(node);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%										 										%
%										 										%
%										 										%
%	P r u n e C h i l d															%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function PruneChild deletes the given node and merges its statistics into
%	its parent.
%
%	The format of the PruneSubtree routine is:
%
%		PruneChild(node)
%
%	A description of each parameter follows.
%
%	o node: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void PruneChild(node)
Node *node;
{
	Node *parent;

	/*
	Merge color statistics into parent.
	*/
	parent=node->parent;
	parent->children &= ~(1 << node->id);
	parent->number_unique += node->number_unique;
	parent->total_red += node->total_red;
	parent->total_green += node->total_green;
	parent->total_blue += node->total_blue;
	cube.nodes--;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%										 										%
%										 										%
%										 										%
%	P r u n e L e v e l															%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Procedure PruneLevel deletes all nodes at the bottom level of the color
%	tree merging their color statistics into their parent node.
%
%	The format of the PruneLevel routine is:
%
%		PruneLevel(node)
%
%	A description of each parameter follows.
%
%	o node: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void PruneLevel(node)
Node *node;
{
	int id;

	/*
	Traverse any children.
	*/
	if (node->children != 0)
		for (id=0; id < 8; id++)
			if (node->children & (1 << id))
				PruneLevel(node->child[id]);
	if (node->level == (cube.depth-1))
		PruneChild(node);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%										 										%
%										 										%
%										 										%
%	R e d u c e																	%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function Reduce traverses the color cube tree and prunes any node whose
%	number of colors fall below a particular threshold.
%
%	The format of the Reduce routine is:
%
%		Reduce(node)
%
%	A description of each parameter follows.
%
%	o node: pointer to node in color cube tree that is to be pruned.
%
%
*/
static void Reduce(node)
Node *node;
{
	dword id;

	/*
	Traverse any children.
	*/
	if (node->children != 0)
		for (id=0; id < 8; id++)
			if (node->children & (1 << id))
				Reduce(node->child[id]);

	if (node->number_colors <= cube.pruning_threshold)
	{
		/*
		Node has a sub-threshold color count so prune it.	Node is an colormap
		entry if parent does not have any unique colors.
		*/
		if (node->parent->number_unique == 0)
			cube.colors++;
		PruneChild(node);
		if (node->parent->number_colors < cube.next_pruning_threshold)
			cube.next_pruning_threshold=node->parent->number_colors;
	}
	else
	{
		/*
		Find minimum pruning threshold.	Node is a colormap entry if it has
		unique colors.
		*/
		if (node->number_unique > 0)
			cube.colors++;
		if (node->number_colors < cube.next_pruning_threshold)
			cube.next_pruning_threshold=node->number_colors;
	}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%										 										%
%										 										%
%										 										%
%	R e d u c t i o n															%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function Reduction repeatedly prunes the tree until the number of nodes
%	with n2 > 0 is less than or equal to the maximum number of colors allowed
%	in the output image.	On any given iteration over the tree, it selects
%	those nodes whose n1	count is minimal for pruning and merges their
%	color statistics upward. It uses a pruning threshold, ns, to govern
%	node selection as follows:
%
%	ns = 0
%	while number of nodes with (n2 > 0) > required maximum number of colors
%		prune all nodes such that n1 <= ns
%		Set ns to minimum n1 in remaining nodes
%
%	When a node to be pruned has offspring, the pruning procedure invokes
%	itself recursively in order to prune the tree from the leaves upward.
%	n2,	Sr, Sg,	and	Sb in a node being pruned are always added to the
%	corresponding data in that node's parent.	This retains the pruned
%	node's color characteristics for later averaging.
%
%	For each node, n2 pixels exist for which that node represents the
%	smallest volume in RGB space containing those pixel's colors.	When n2
%	> 0 the node will uniquely define a color in the output image. At the
%	beginning of reduction,	n2 = 0	for all nodes except a the leaves of
%	the tree which represent colors present in the input image.
%
%	The other pixel count, n1, indicates the total number of colors
%	within the cubic volume which the node represents.	This includes n1 -
%	n2	pixels whose colors should be defined by nodes at a lower level in
%	the tree.
%
%	The format of the Reduction routine is:
%
%		Reduction(number_colors)
%
%	A description of each parameter follows.
%
%	o number_colors: This integer value indicates the maximum number of
%		colors in the quantized image or colormap.	The actual number of
%		colors allocated to the colormap may be less than this value, but
%		never more.	Note, the number of colors is restricted to a value
%		less than or equal to 65536 if the continuous_tone parameter has a
%		value of zero.
%
%
*/
static void Reduction(number_colors)
dword number_colors;
{
	cube.next_pruning_threshold=1;
	while (cube.colors > number_colors)
	{
		cube.pruning_threshold=cube.next_pruning_threshold;
		cube.next_pruning_threshold=cube.root->number_colors-1;
		cube.colors=0;
		Reduce(cube.root);
		myevent();
	}
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%										 										%
%										 										%
%										 										%
%	Q u a n t i z e I m a g e													%
%										 										%
%										 										%
%										 										%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Function QuantizeImage analyzes the colors within a reference image and
%	chooses a fixed number of colors to represent the image.	The goal of the
%	algorithm is to minimize the difference between the input and output image
%	while minimizing the processing time.
%
%	The format of the QuantizeImage routine is:
%
%		colors=QuantizeImage(image,number_colors,tree_depth,dither,optimal)
%
%	A description of each parameter follows.
%
%	o colors: The QuantizeImage function returns this integer
%		value.	It is the actual number of colors allocated in the
%		colormap.	Note, the actual number of colors allocated may be less
%		than the number of colors requested, but never more.
%
%	o image: Specifies a pointer to an Image structure;	returned from
%		ReadImage.
%
%	o number_colors: This integer value indicates the maximum number of
%		colors in the quantized image or colormap.	The actual number of
%		colors allocated to the colormap may be less than this value, but
%		never more.	Note, the number of colors is restricted to a value
%		less than or equal to 65536 if the continuous_tone parameter has a
%		value of zero.
%
%	o tree_depth: Normally, this integer value is zero or one.	A zero or
%		one tells Quantize to choose a optimal tree depth of Log4(number_colors).
%		A tree of this depth generally allows the best representation of the
%		reference image with the least amount of memory and the fastest
%		computational speed.	In some cases, such as an image with low color
%		dispersion (a few number of colors), a value other than
%		Log4(number_colors) is required.	To expand the color tree completely,
%		use a value of 8.
%
%	o dither: Set this integer value to something other than zero to
%		dither the quantized image.	The basic strategy of dithering is to
%		trade intensity resolution for spatial resolution by averaging the
%		intensities of several neighboring pixels.	Images which suffer
%		from severe contouring when quantized can be improved with the
%		technique of dithering.	Severe contouring generally occurs when
%		quantizing to very few colors, or to a poorly-chosen colormap.
%		Note, dithering is a computationally expensive process and will
%		increase processing time significantly.
%
%	o colorspace: An dwordeger value that indicates the colorspace.
%		Empirical evidence suggests that distances in YUV or YIQ correspond to
%		perceptual color differences more closely than do distances in RGB
%		space.	The image is then returned to RGB colorspace after color
%		reduction.
%
%	o optimal: An dwordeger value greater than zero indicates that
%		the optimal representation of the reference image should be returned.
%
%
*/
void QuantizeImage(image,number_colors,tree_depth,dither,colorspace,optimal)
ImageMagick *image;
dword number_colors, tree_depth, dither, colorspace, optimal;
{
	Nodes *nodes;

	/*
	Reduce the number of colors in the continuous tone image.
	*/
	if (number_colors > MaxColormapSize)
		number_colors=MaxColormapSize;

	if(app_data.verbose)
		fprintf(stderr,"xslideshow: quantize() InitializeCube\n");
	InitializeCube(number_colors,tree_depth,image->columns*image->rows,optimal);
	dither|=!optimal;

	myevent();

	if(app_data.verbose)
		fprintf(stderr,"xslideshow: quantize() Classification\n");
	Classification(image);

	myevent();

	if(app_data.verbose)
		fprintf(stderr,"xslideshow: quantize() Reduction\n");
	Reduction(number_colors);

	myevent();

	if(app_data.verbose)
		fprintf(stderr,"xslideshow: quantize() Assignment\n");
	Assignment(image,dither,colorspace,optimal);

	myevent();

	/*
	Release color cube tree storage.
	*/
	do {
		nodes=cube.node_queue->next;
		(void) XtFree((char *) cube.node_queue);
		cube.node_queue=nodes;
	} while (cube.node_queue != (Nodes *) NULL);
}


#if defined(__STDC__) || defined(__cplusplus)
void quantize(int numcolor)
#else
void quantize(numcolor)
int numcolor;
#endif
{
ImageMagick *image;
byte *dst,*src;
int i;

	image = (ImageMagick *)XtCalloc(1, sizeof(ImageMagick));
	image->columns = gim.subImageList->width;
	image->rows	   = gim.subImageList->height;
	image->packets = image->columns * image->rows;

	if((image->pixels=(ColorPacket *)XtMalloc((dword)image->packets * sizeof(ColorPacket)))==NULL){
		fprintf(stderr,"xslideshow: quantize() memory allocation error\n");
		goodbyekiss();
	}

	for(	src = gim.subImageList->image, i = 0;
			i < (int)image->packets;
			i++	){
		if(gim.subImageList->bits_per_pixel == 8) {
			image->pixels[i].red   = (dword)gim.subImageList->red[*src];
			image->pixels[i].green = (dword)gim.subImageList->green[*src];
			image->pixels[i].blue  = (dword)gim.subImageList->blue[*src++];
		}
		else {
			image->pixels[i].red   = *src++;
			image->pixels[i].green = *src++;
			image->pixels[i].blue  = *src++;
		}
		image->pixels[i].index = 0;
	}
	XtFree((char *)(gim.subImageList->image));
	gim.subImageList->image = (byte *)NULL;


	/* Quanitze Image */
	QuantizeImage(image, numcolor, 8, False, RGBColorspace, True);


	/* Create the new colormap */
	for (i = 0; i < (int)image->colors; i++) {
		gim.subImageList->red[i]   = image->colormap[i].red;
		gim.subImageList->green[i] = image->colormap[i].green;
		gim.subImageList->blue[i]  = image->colormap[i].blue;
	}
	gim.subImageList->mapsize = image->colors;
	XtFree((char *)(image->colormap));


	/* Create the new image */
	if((dst=(byte *)XtMalloc(gim.subImageList->width * gim.subImageList->height * sizeof(byte)))==NULL){
		fprintf(stderr,"xslideshow: quantize() memory allocation error\n");
		goodbyekiss();
	}

	for(i = 0; i < (int)image->packets; i++)
			dst[i] = (byte)(image->pixels[i].index);

	XtFree((char *)(image->pixels));
	XtFree((char *)image);

	gim.subImageList->image = dst;
	gim.subImageList->bits_per_pixel = 8;

	if(app_data.verbose)
		fprintf(stderr,"xslideshow: quantize() done.\n");
}