summaryrefslogtreecommitdiffstats
path: root/generic/tkImgGIF.c
blob: 9d116310311ed96a362478c4eb07355256a49686 (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
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
/*
 * tkImgGIF.c --
 *
 *	A photo image file handler for GIF files. Reads 87a and 89a GIF files.
 *	At present, there only is a file write function. GIF images may be
 *	read using the -data option of the photo image. The data may be given
 *	as a binary string in a Tcl_Obj or by representing the data as BASE64
 *	encoded ascii.  Derived from the giftoppm code found in the pbmplus
 *	package and tkImgFmtPPM.c in the tk4.0b2 distribution.
 *
 * Copyright (c) Reed Wade (wade@cs.utk.edu), University of Tennessee
 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
 * Copyright (c) 1997 Australian National University
 * Copyright (c) 2005 Donal K. Fellows
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * This file also contains code from the giftoppm program, which is
 * copyrighted as follows:
 *
 * +--------------------------------------------------------------------+
 * | Copyright 1990, David Koblas.					|
 * |   Permission to use, copy, modify, and distribute this software	|
 * |   and its documentation for any purpose and without fee is hereby	|
 * |   granted, provided that the above copyright notice appear in all	|
 * |   copies and that both that copyright notice and this permission	|
 * |   notice appear in supporting documentation.  This software is	|
 * |   provided "as is" without express or implied warranty.		|
 * +--------------------------------------------------------------------+
 *
 * This file also contains code from miGIF. See lower down in file for the
 * applicable copyright notice for that portion.
 *
 * RCS: @(#) $Id: tkImgGIF.c,v 1.27 2005/06/19 21:49:08 dkf Exp $
 */

/*
 * GIF's are represented as data in either binary or base64 format.  base64
 * strings consist of 4 6-bit characters -> 3 8 bit bytes.  A-Z, a-z, 0-9, +
 * and / represent the 64 values (in order).  '=' is a trailing padding char
 * when the un-encoded data is not a multiple of 3 bytes.  We'll ignore white
 * space when encountered.  Any other invalid character is treated as an EOF
 */

#define GIF_SPECIAL	(256)
#define GIF_PAD		(GIF_SPECIAL+1)
#define GIF_SPACE	(GIF_SPECIAL+2)
#define GIF_BAD		(GIF_SPECIAL+3)
#define GIF_DONE	(GIF_SPECIAL+4)

/*
 * structure to "mimic" FILE for Mread, so we can look like fread.  The
 * decoder state keeps track of which byte we are about to read, or EOF.
 */

typedef struct mFile {
    unsigned char *data;	/* mmencoded source string */
    int c;			/* bits left over from previous character */
    int state;			/* decoder state (0-4 or GIF_DONE) */
    int length;			/* Total amount of bytes in data */
} MFile;

#include "tkInt.h"
#include "tkPort.h"

/*
 * Non-ASCII encoding support:
 * Most data in a GIF image is binary and is treated as such. However, a few
 * key bits are stashed in ASCII. If we try to compare those pieces to the
 * char they represent, it will fail on any non-ASCII (eg, EBCDIC) system. To
 * accomodate these systems, we test against the numeric value of the ASCII
 * characters instead of the characters themselves. This is encoding
 * independant.
 */

static CONST char GIF87a[] = {			/* ASCII GIF87a */
    0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x00
};
static CONST char GIF89a[] = {			/* ASCII GIF89a */
    0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x00
};
#define GIF_TERMINATOR	0x3b			/* ASCII ; */
#define GIF_EXTENSION	0x21			/* ASCII ! */
#define GIF_START	0x2c			/* ASCII , */

#define INLINE_DATA_BINARY	((const char *) 0x01)
#define INLINE_DATA_BASE64	((const char *) 0x02)

/*
 *			HACK ALERT!!  HACK ALERT!!  HACK ALERT!!
 * This code is hard-wired for reading from files. In order to read from a
 * data stream, we'll trick fread so we can reuse the same code. 0==from file;
 * 1==from base64 encoded data; 2==from binary data
 */

typedef struct {
    const char *fromData;
    unsigned char workingBuffer[280];
    struct {
	int bytes;
	int done;
	unsigned int window;
	int bitsInWindow;
	unsigned char *c;
    } reader;
} GIFImageConfig;

/*
 * The format record for the GIF file format:
 */

static int	FileMatchGIF _ANSI_ARGS_((Tcl_Channel chan, CONST char *fileName,
		    Tcl_Obj *format, int *widthPtr, int *heightPtr,
		    Tcl_Interp *interp));
static int	FileReadGIF _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Channel chan,
		    CONST char *fileName, Tcl_Obj *format,
		    Tk_PhotoHandle imageHandle, int destX, int destY,
		    int width, int height, int srcX, int srcY));
static int	StringMatchGIF _ANSI_ARGS_(( Tcl_Obj *dataObj, Tcl_Obj *format,
		    int *widthPtr, int *heightPtr, Tcl_Interp *interp));
static int	StringReadGIF _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *dataObj,
		    Tcl_Obj *format, Tk_PhotoHandle imageHandle,
		    int destX, int destY, int width, int height,
		    int srcX, int srcY));
static int 	FileWriteGIF _ANSI_ARGS_((Tcl_Interp *interp,
		    CONST char *filename, Tcl_Obj *format,
		    Tk_PhotoImageBlock *blockPtr));
static int	CommonWriteGIF _ANSI_ARGS_((Tcl_Interp *interp,
		    Tcl_Channel handle, Tcl_Obj *format,
		    Tk_PhotoImageBlock *blockPtr));

Tk_PhotoImageFormat tkImgFmtGIF = {
    "gif",		/* name */
    FileMatchGIF,	/* fileMatchProc */
    StringMatchGIF,	/* stringMatchProc */
    FileReadGIF,	/* fileReadProc */
    StringReadGIF,	/* stringReadProc */
    FileWriteGIF,	/* fileWriteProc */
    NULL,		/* stringWriteProc */
};

#define INTERLACE		0x40
#define LOCALCOLORMAP		0x80
#define BitSet(byte, bit)	(((byte) & (bit)) == (bit))
#define MAXCOLORMAPSIZE		256
#define CM_RED			0
#define CM_GREEN		1
#define CM_BLUE			2
#define CM_ALPHA		3
#define MAX_LWZ_BITS		12
#define LM_to_uint(a,b)		(((b)<<8)|(a))

/*
 * Prototypes for local procedures defined in this file:
 */

static int	DoExtension _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    Tcl_Channel chan, int label, unsigned char *buffer,
		    int *transparent));
static int	GetCode _ANSI_ARGS_((Tcl_Channel chan, int code_size, int flag,
		    GIFImageConfig *gifConfPtr));
static int	GetDataBlock _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    Tcl_Channel chan, unsigned char *buf));
static int	ReadColorMap _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    Tcl_Channel chan, int number,
		    unsigned char buffer[MAXCOLORMAPSIZE][4]));
static int	ReadGIFHeader _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    Tcl_Channel chan, int *widthPtr, int *heightPtr));
static int	ReadImage _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    Tcl_Interp *interp, char *imagePtr, Tcl_Channel chan,
		    int len, int rows, unsigned char cmap[MAXCOLORMAPSIZE][4],
		    int width, int height, int srcX, int srcY, int interlace,
		    int transparent));

/*
 * these are for the BASE64 image reader code only
 */

static int	Fread _ANSI_ARGS_((GIFImageConfig *gifConfPtr,
		    unsigned char *dst, size_t size, size_t count,
		    Tcl_Channel chan));
static int	Mread _ANSI_ARGS_((unsigned char *dst, size_t size,
		    size_t count, MFile *handle));
static int	Mgetc _ANSI_ARGS_((MFile *handle));
static int	char64 _ANSI_ARGS_((int c));
static void	mInit _ANSI_ARGS_((unsigned char *string, MFile *handle,
		    int length));

/*
 *----------------------------------------------------------------------
 *
 * FileMatchGIF --
 *
 *	This procedure is invoked by the photo image type to see if a file
 *	contains image data in GIF format.
 *
 * Results:
 *	The return value is 1 if the first characters in file f look like GIF
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchGIF(chan, fileName, format, widthPtr, heightPtr, interp)
    Tcl_Channel chan;		/* The image file, open for reading. */
    CONST char *fileName;	/* The name of the image file. */
    Tcl_Obj *format;		/* User-specified format object, or NULL. */
    int *widthPtr, *heightPtr;	/* The dimensions of the image are returned
				 * here if the file is a valid raw GIF file. */
    Tcl_Interp *interp;		/* not used */
{
    GIFImageConfig gifConf;

    memset(&gifConf, 0, sizeof(GIFImageConfig));
    return ReadGIFHeader(&gifConf, chan, widthPtr, heightPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * FileReadGIF --
 *
 *	This procedure is called by the photo image type to read GIF format
 *	data from a file and write it into a given photo image.
 *
 * Results:
 *	A standard TCL completion code.  If TCL_ERROR is returned then an
 *	error message is left in the interp's result.
 *
 * Side effects:
 *	The access position in file f is changed, and new data is added to the
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadGIF(interp, chan, fileName, format, imageHandle, destX, destY,
	width, height, srcX, srcY)
    Tcl_Interp *interp;		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan;		/* The image file, open for reading. */
    CONST char *fileName;	/* The name of the image file. */
    Tcl_Obj *format;		/* User-specified format object, or NULL. */
    Tk_PhotoHandle imageHandle;	/* The photo image to write into. */
    int destX, destY;		/* Coordinates of top-left pixel in photo
				 * image to be written to. */
    int width, height;		/* Dimensions of block of photo image to be
				 * written to. */
    int srcX, srcY;		/* Coordinates of top-left pixel to be used in
				 * image being read. */
{
    int fileWidth, fileHeight;
    int nBytes, index = 0, argc = 0, i;
    Tcl_Obj **objv;
    Tk_PhotoImageBlock block;
    unsigned char buf[100];
    unsigned char *trashBuffer = NULL;
    int bitPixel;
    unsigned char colorMap[MAXCOLORMAPSIZE][4];
    int transparent = -1;
    static CONST char *optionStrings[] = {
	"-index",	NULL
    };
    GIFImageConfig gifConf, *gifConfPtr = &gifConf;

    /*
     * Decode the magic used to convey when we're sourcing data from a string
     * source and not a file.
     */

    memset(gifConfPtr, 0, sizeof(GIFImageConfig));
    if (fileName == INLINE_DATA_BINARY || fileName == INLINE_DATA_BASE64) {
	gifConfPtr->fromData = fileName;
	fileName = "inline data";
    }

    if (format && Tcl_ListObjGetElements(interp, format,
	    &argc, &objv) != TCL_OK) {
	return TCL_ERROR;
    }
    for (i = 1; i < argc; i++) {
	if (Tcl_GetIndexFromObj(interp, objv[i], optionStrings, "option name",
		0, &nBytes) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (i == (argc-1)) {
	    Tcl_AppendResult(interp, "no value given for \"",
		    Tcl_GetString(objv[i]), "\" option", (char *) NULL);
	    return TCL_ERROR;
	}
	if (Tcl_GetIntFromObj(interp, objv[++i], &index) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if (!ReadGIFHeader(gifConfPtr, chan, &fileWidth, &fileHeight)) {
    	Tcl_AppendResult(interp, "couldn't read GIF header from file \"",
		fileName, "\"", NULL);
	return TCL_ERROR;
    }
    if ((fileWidth <= 0) || (fileHeight <= 0)) {
	Tcl_AppendResult(interp, "GIF image file \"", fileName,
		"\" has dimension(s) <= 0", (char *) NULL);
	return TCL_ERROR;
    }

    if (Fread(gifConfPtr, buf, 1, 3, chan) != 3) {
	return TCL_OK;
    }
    bitPixel = 2<<(buf[0]&0x07);

    if (BitSet(buf[0], LOCALCOLORMAP)) {	/* Global Colormap */
	if (!ReadColorMap(gifConfPtr, chan, bitPixel, colorMap)) {
	    Tcl_AppendResult(interp, "error reading color map",
		    (char *) NULL);
	    return TCL_ERROR;
	}
    }

    if ((srcX + width) > fileWidth) {
	width = fileWidth - srcX;
    }
    if ((srcY + height) > fileHeight) {
	height = fileHeight - srcY;
    }
    if ((width <= 0) || (height <= 0)
	    || (srcX >= fileWidth) || (srcY >= fileHeight)) {
	return TCL_OK;
    }

    if (Tk_PhotoExpand(interp, imageHandle,
	    destX + width, destY + height) != TCL_OK) {
	return TCL_ERROR;
    }

    block.width = width;
    block.height = height;
    block.pixelSize = 4;
    block.pitch = block.pixelSize * block.width;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    block.pixelPtr = NULL;

    while (1) {
	if (Fread(gifConfPtr, buf, 1, 1, chan) != 1) {
	    /*
	     * Premature end of image.
	     */

	    Tcl_AppendResult(interp,
		    "premature end of image data for this index",
		    (char *) NULL);
	    goto error;
	}

	if (buf[0] == GIF_TERMINATOR) {
	    /*
	     * GIF terminator.
	     */

	    Tcl_AppendResult(interp, "no image data for this index",
		    (char *) NULL);
	    goto error;
	}

	if (buf[0] == GIF_EXTENSION) {
	    /*
	     * This is a GIF extension.
	     */

	    if (Fread(gifConfPtr, buf, 1, 1, chan) != 1) {
		Tcl_SetResult(interp,
			"error reading extension function code in GIF image",
			TCL_STATIC);
		goto error;
	    }
	    if (DoExtension(gifConfPtr, chan, buf[0],
		    gifConfPtr->workingBuffer, &transparent) < 0) {
		Tcl_SetResult(interp, "error reading extension in GIF image",
			TCL_STATIC);
		goto error;
	    }
	    continue;
	}

	if (buf[0] != GIF_START) {
	    /*
	     * Not a valid start character; ignore it.
	     */
	    continue;
	}

	if (Fread(gifConfPtr, buf, 1, 9, chan) != 9) {
	    Tcl_SetResult(interp,
		    "couldn't read left/top/width/height in GIF image",
		    TCL_STATIC);
	    goto error;
	}

	fileWidth = LM_to_uint(buf[4], buf[5]);
	fileHeight = LM_to_uint(buf[6], buf[7]);

	bitPixel = 1<<((buf[8]&0x07)+1);

	if (index--) {
	    /*
	     * This is not the image we want to read: skip it.
	     */
	    if (BitSet(buf[8], LOCALCOLORMAP)) {
		if (!ReadColorMap(gifConfPtr, chan, bitPixel, colorMap)) {
		    Tcl_AppendResult(interp,
			    "error reading color map", (char *) NULL);
		    goto error;
		}
	    }

	    /*
	     * If we've not yet allocated a trash buffer, do so now.
	     */
	    if (trashBuffer == NULL) {
		nBytes = fileWidth * fileHeight * 3;
		trashBuffer = (unsigned char *) ckalloc((unsigned int) nBytes);
	    }

	    /*
	     * Slurp!  Process the data for this image and stuff it in a trash
	     * buffer.
	     *
	     * Yes, it might be more efficient here to *not* store the data
	     * (we're just going to throw it away later). However, I elected
	     * to implement it this way for good reasons. First, I wanted to
	     * avoid duplicating the (fairly complex) LWZ decoder in
	     * ReadImage. Fine, you say, why didn't you just modify it to
	     * allow the use of a NULL specifier for the output buffer? I
	     * tried that, but it negatively impacted the performance of what
	     * I think will be the common case: reading the first image in the
	     * file. Rather than marginally improve the speed of the less
	     * frequent case, I chose to maintain high performance for the
	     * common case.
	     */

	    if (ReadImage(gifConfPtr, interp, (char *)trashBuffer, chan,
		    fileWidth, fileHeight, colorMap, 0, 0, 0, 0, 0,
		    -1) != TCL_OK) {
		goto error;
	    }
	    continue;
	}

	if (BitSet(buf[8], LOCALCOLORMAP)) {
	    if (!ReadColorMap(gifConfPtr, chan, bitPixel, colorMap)) {
		    Tcl_AppendResult(interp, "error reading color map", 
			    (char *) NULL);
		    goto error;
	    }
	}

	index = LM_to_uint(buf[0], buf[1]);
	srcX -= index;
	if (srcX<0) {
	    destX -= srcX; width += srcX;
	    srcX = 0;
	}

	if (width > fileWidth) {
	    width = fileWidth;
	}

	index = LM_to_uint(buf[2], buf[3]);
	srcY -= index;
	if (index > srcY) {
	    destY -= srcY; height += srcY;
	    srcY = 0;
	}
	if (height > fileHeight) {
	    height = fileHeight;
	}

	if ((width <= 0) || (height <= 0)) {
	    block.pixelPtr = 0;
	    goto noerror;
	}

	block.width = width;
	block.height = height;
	block.pixelSize = (transparent>=0) ? 4 : 3;
	block.offset[3] = (transparent>=0) ? 3 : 0;
	block.pitch = block.pixelSize * fileWidth;
	nBytes = block.pitch * fileHeight;
	block.pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes);

	if (ReadImage(gifConfPtr, interp, (char *) block.pixelPtr, chan,
		fileWidth, fileHeight, colorMap, fileWidth, fileHeight, srcX,
		srcY, BitSet(buf[8], INTERLACE), transparent) != TCL_OK) {
	    goto error;
	}
	break;
    }

    if (Tk_PhotoPutBlock(interp, imageHandle, &block, destX, destY,
	    width, height, TK_PHOTO_COMPOSITE_SET) != TCL_OK) {
	goto error;
    }

  noerror:
    /*
     * If a trash buffer has been allocated, free it now.
     */
    if (trashBuffer != NULL) {
	ckfree((char *)trashBuffer);
    }
    if (block.pixelPtr) {
	ckfree((char *) block.pixelPtr);
    }
    Tcl_AppendResult(interp, tkImgFmtGIF.name, (char *) NULL);
    return TCL_OK;

  error:
    /*
     * If a trash buffer has been allocated, free it now.
     */
    if (trashBuffer != NULL) {
	ckfree((char *)trashBuffer);
    }
    if (block.pixelPtr) {
	ckfree((char *) block.pixelPtr);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchGIF --
 *
 *	This procedure is invoked by the photo image type to see if an object
 *	contains image data in GIF format.
 *
 * Results:
 *	The return value is 1 if the first characters in the data are like GIF
 *	data, and 0 otherwise.
 *
 * Side effects:
 *	The size of the image is placed in widthPtr and heightPtr.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchGIF(dataObj, format, widthPtr, heightPtr, interp)
    Tcl_Obj *dataObj;		/* the object containing the image data */
    Tcl_Obj *format;		/* the image format object, or NULL */
    int *widthPtr;		/* where to put the string width */
    int *heightPtr;		/* where to put the string height */
    Tcl_Interp *interp;		/* not used */
{
    unsigned char *data, header[10];
    int got, length;
    MFile handle;

    data = Tcl_GetByteArrayFromObj(dataObj, &length);

    /*
     * Header is a minimum of 10 bytes.
     */
    if (length < 10) {
	return 0;
    }

    /*
     * Check whether the data is Base64 encoded.
     */

    if ((strncmp(GIF87a, (char *) data, 6) != 0) && 
	    (strncmp(GIF89a, (char *) data, 6) != 0)) {
	/*
	 * Try interpreting the data as Base64 encoded
	 */
	mInit((unsigned char *) data, &handle, length);
	got = Mread(header, 10, 1, &handle);
	if (got != 10
		|| ((strncmp(GIF87a, (char *) header, 6) != 0)
		&& (strncmp(GIF89a, (char *) header, 6) != 0))) {
	    return 0;
	}
    } else {
	memcpy((VOID *) header, (VOID *) data, 10);
    }
    *widthPtr = LM_to_uint(header[6], header[7]);
    *heightPtr = LM_to_uint(header[8], header[9]);
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadGIF --
 *
 *	This procedure is called by the photo image type to read GIF format
 *	data from an object, optionally base64 encoded, and give it to the
 *	photo image.
 *
 * Results:
 *	A standard TCL completion code.  If TCL_ERROR is returned then an
 *	error message is left in the interp's result.
 *
 * Side effects:
 *	New data is added to the image given by imageHandle.  This procedure
 *	calls FileReadGIF by redefining the operation of fprintf temporarily.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadGIF(interp, dataObj, format, imageHandle,
	destX, destY, width, height, srcX, srcY)
    Tcl_Interp *interp;		/* interpreter for reporting errors in */
    Tcl_Obj *dataObj;		/* object containing the image */
    Tcl_Obj *format;		/* format object, or NULL */
    Tk_PhotoHandle imageHandle;	/* the image to write this data into */
    int destX, destY;		/* The rectangular region of the */
    int width, height;		/* image to copy */
    int srcX, srcY;
{
    MFile handle;
    int length;
    char *data = (char *) Tcl_GetByteArrayFromObj(dataObj, &length);

    mInit((unsigned char *)data, &handle, length);

    if (strncmp(GIF87a, data, 6) && strncmp(GIF89a, data, 6)) {
	/*
	 * Check whether the data is Base64 encoded by doing a
	 * character-by-charcter comparison with the binary-format headers;
	 * BASE64-encoded never matches (matching the other way is harder
	 * because of potential padding).
	 */

	return FileReadGIF(interp, (Tcl_Channel) &handle, INLINE_DATA_BASE64,
		format, imageHandle, destX, destY, width, height, srcX, srcY);
    } else {
	return FileReadGIF(interp, (Tcl_Channel) &handle, INLINE_DATA_BINARY,
		format, imageHandle, destX, destY, width, height, srcX, srcY);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ReadGIFHeader --
 *
 *	This procedure reads the GIF header from the beginning of a GIF file
 *	and returns the dimensions of the image.
 *
 * Results:
 *	The return value is 1 if file "f" appears to start with a valid GIF
 *	header, 0 otherwise.  If the header is valid, then *widthPtr and
 *	*heightPtr are modified to hold the dimensions of the image.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadGIFHeader(gifConfPtr, chan, widthPtr, heightPtr)
    GIFImageConfig *gifConfPtr;
    Tcl_Channel chan;		/* Image file to read the header from */
    int *widthPtr, *heightPtr;	/* The dimensions of the image are returned
				 * here. */
{
    unsigned char buf[7];

    if ((Fread(gifConfPtr, buf, 1, 6, chan) != 6)
	    || ((strncmp(GIF87a, (char *) buf, 6) != 0)
	    && (strncmp(GIF89a, (char *) buf, 6) != 0))) {
	return 0;
    }

    if (Fread(gifConfPtr, buf, 1, 4, chan) != 4) {
	return 0;
    }

    *widthPtr = LM_to_uint(buf[0], buf[1]);
    *heightPtr = LM_to_uint(buf[2], buf[3]);
    return 1;
}

/*
 *-----------------------------------------------------------------
 * The code below is copied from the giftoppm program and modified
 * just slightly.
 *-----------------------------------------------------------------
 */

static int
ReadColorMap(gifConfPtr, chan, number, buffer)
    GIFImageConfig *gifConfPtr;
    Tcl_Channel chan;
    int number;
    unsigned char buffer[MAXCOLORMAPSIZE][4];
{
    int i;
    unsigned char rgb[3];

    for (i = 0; i < number; ++i) {
	if (Fread(gifConfPtr, rgb, sizeof(rgb), 1, chan) <= 0) {
	    return 0;
	}

	if (buffer) {
	    buffer[i][CM_RED] = rgb[0];
	    buffer[i][CM_GREEN] = rgb[1];
	    buffer[i][CM_BLUE] = rgb[2];
	    buffer[i][CM_ALPHA] = 255;
	}
    }
    return 1;
}

static int
DoExtension(gifConfPtr, chan, label, buf, transparent)
    GIFImageConfig *gifConfPtr;
    Tcl_Channel chan;
    int label;
    unsigned char *buf;
    int *transparent;
{
    int count;

    switch (label) {
    case 0x01:		/* Plain Text Extension */
	break;

    case 0xff:		/* Application Extension */
	break;

    case 0xfe:		/* Comment Extension */
	do {
	    count = GetDataBlock(gifConfPtr, chan, (unsigned char*) buf);
	} while (count > 0);
	return count;

    case 0xf9:		/* Graphic Control Extension */
	count = GetDataBlock(gifConfPtr, chan, (unsigned char*) buf);
	if (count < 0) {
	    return 1;
	}
	if ((buf[0] & 0x1) != 0) {
	    *transparent = buf[3];
	}

	do {
	    count = GetDataBlock(gifConfPtr, chan, (unsigned char*) buf);
	} while (count > 0);
	return count;
    }

    do {
	count = GetDataBlock(gifConfPtr, chan, (unsigned char*) buf);
    } while (count > 0);
    return count;
}

static int
GetDataBlock(gifConfPtr, chan, buf)
    GIFImageConfig *gifConfPtr;
    Tcl_Channel chan;
    unsigned char *buf;
{
    unsigned char count;

    if (Fread(gifConfPtr, &count, 1, 1, chan) <= 0) {
	return -1;
    }

    if ((count != 0) && (Fread(gifConfPtr, buf, count, 1, chan) <= 0)) {
	return -1;
    }

    return count;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadImage --
 *
 *	Process a GIF image from a given source, with a given height, width,
 *	transparency, etc.
 *
 *	This code is based on the code found in the ImageMagick GIF decoder,
 *	which is (c) 2000 ImageMagick Studio.
 *
 *	Some thoughts on our implementation:
 *	It sure would be nice if ReadImage didn't take 11 parameters! I think
 *	that if we were smarter, we could avoid doing that.
 *
 *	Possible further optimizations: we could pull the GetCode function
 *	directly into ReadImage, which would improve our speed.
 *
 * Results:
 *	Processes a GIF image and loads the pixel data into a memory array.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ReadImage(gifConfPtr, interp, imagePtr, chan, len, rows, cmap,
	width, height, srcX, srcY, interlace, transparent)
    GIFImageConfig *gifConfPtr;
    Tcl_Interp *interp;
    char *imagePtr;
    Tcl_Channel chan;
    int len, rows;
    unsigned char cmap[MAXCOLORMAPSIZE][4];
    int width, height;
    int srcX, srcY;
    int interlace;
    int transparent;
{
    unsigned char initialCodeSize;
    int v;
    int xpos = 0, ypos = 0, pass = 0, i;
    register char *pixelPtr;
    CONST static int interlaceStep[] = { 8, 8, 4, 2 };
    CONST static int interlaceStart[] = { 0, 4, 2, 1 };
    unsigned short prefix[(1 << MAX_LWZ_BITS)];
    unsigned char append[(1 << MAX_LWZ_BITS)];
    unsigned char stack[(1 << MAX_LWZ_BITS)*2];
    register unsigned char *top;
    int codeSize, clearCode, inCode, endCode, oldCode, maxCode;
    int code, firstCode;

    /*
     * Initialize the decoder
     */
    if (Fread(gifConfPtr, &initialCodeSize, 1, 1, chan) <= 0) {
	Tcl_AppendResult(interp, "error reading GIF image: ",
		Tcl_PosixError(interp), (char *) NULL);
	return TCL_ERROR;
    }
    if (transparent != -1) {
	cmap[transparent][CM_RED] = 0;
	cmap[transparent][CM_GREEN] = 0;
	cmap[transparent][CM_BLUE] = 0;
	cmap[transparent][CM_ALPHA] = 0;
    }

    pixelPtr = imagePtr;

    /*
     * Initialize the decoder.
     *
     * Set values for "special" numbers:
     * clear code	reset the decoder
     * end code		stop decoding
     * code size	size of the next code to retrieve
     * max code		next available table position
     */
    clearCode = 1 << (int) initialCodeSize;
    endCode = clearCode + 1;
    codeSize = (int) initialCodeSize + 1;
    maxCode = clearCode + 2;
    oldCode = -1;
    firstCode = -1;
    
    memset((void *)prefix, 0, (1 << MAX_LWZ_BITS) * sizeof(short));
    memset((void *)append, 0, (1 << MAX_LWZ_BITS) * sizeof(char));
    for (i = 0; i < clearCode; i++) {
	append[i] = i;
    }
    top = stack;

    GetCode(chan, 0, 1, gifConfPtr);

    /*
     * Read until we finish the image
     */
    for (i = 0, ypos = 0; i < rows; i++) {
	for (xpos = 0; xpos < len; ) {

	    if (top == stack) {
		/*
		 * Bummer -- our stack is empty.  Now we have to work!
		 */
		code = GetCode(chan, codeSize, 0, gifConfPtr);
		if (code < 0) {
		    return TCL_OK;
		}

		if (code > maxCode || code == endCode) {
		    /*
		     * If we're doing things right, we should never receive a
		     * code that is greater than our current maximum code.  If
		     * we do, bail, because our decoder does not yet have that
		     * code set up.
		     *
		     * If the code is the magic endCode value, quit.
		     */
		    return TCL_OK;
		}

		if (code == clearCode) {
		    /*
		     * Reset the decoder.
		     */
		    codeSize = initialCodeSize + 1;
		    maxCode = clearCode + 2;
		    oldCode = -1;
		    continue;
		}
		
		if (oldCode == -1) {
		    /*
		     * Last pass reset the decoder, so the first code we see
		     * must be a singleton. Seed the stack with it, and set up
		     * the old/first code pointers for insertion into the
		     * string table. We can't just roll this into the
		     * clearCode test above, because at that point we have not
		     * yet read the next code.
		     */
		    *top++ = append[code];
		    oldCode = code;
		    firstCode = code;
		    continue;
		}
		
		inCode = code;

		if (code == maxCode) {
		    /*
		     * maxCode is always one bigger than our highest assigned
		     * code. If the code we see is equal to maxCode, then we
		     * are about to add a new string to the table. ???
		     */
		    *top++ = firstCode;
		    code = oldCode;
		}

		while (code > clearCode) {
		    /*
		     * Populate the stack by tracing the string in the string
		     * table from its tail to its head
		     */
		    *top++ = append[code];
		    code = prefix[code];
		}
		firstCode = append[code];

		/*
		 * If there's no more room in our string table, quit.
		 * Otherwise, add a new string to the table
		 */
		if (maxCode >= (1 << MAX_LWZ_BITS)) {
		    return TCL_OK;
		}

		/*
		 * Push the head of the string onto the stack.
		 */
		*top++ = firstCode;

		/*
		 * Add a new string to the string table
		 */
		prefix[maxCode] = oldCode;
		append[maxCode] = firstCode;
		maxCode++;

		/*
		 * maxCode tells us the maximum code value we can accept. If
		 * we see that we need more bits to represent it than we are
		 * requesting from the unpacker, we need to increase the
		 * number we ask for.
		 */

		if ((maxCode >= (1 << codeSize))
			&& (maxCode < (1<<MAX_LWZ_BITS))) {
		    codeSize++;
		}
		oldCode = inCode;
	    }

	    /*
	     * Pop the next color index off the stack.
	     */

	    v = *(--top);
	    if (v < 0) {
		return TCL_OK;
	    }

	    /* 
	     * If pixelPtr is null, we're skipping this image (presumably
	     * there are more in the file and we will be called to read one of
	     * them later)
	     */

	    *pixelPtr++ = cmap[v][CM_RED];
	    *pixelPtr++ = cmap[v][CM_GREEN];
	    *pixelPtr++ = cmap[v][CM_BLUE];
	    if (transparent >= 0) {
		*pixelPtr++ = cmap[v][CM_ALPHA];
	    }
	    xpos++;

	}

	/*
	 * If interlacing, the next ypos is not just +1
	 */
	if (interlace) {
	    ypos += interlaceStep[pass];
	    while (ypos >= height) {
		pass++;
		if (pass > 3) {
		    return TCL_OK;
		}
		ypos = interlaceStart[pass];
	    }
	} else {
	    ypos++;
	}
	pixelPtr = imagePtr + (ypos) * len * ((transparent>=0)?4:3);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetCode --
 *
 *	Extract the next compression code from the file.  In GIF's, the
 *	compression codes are between 3 and 12 bits long and are then packed
 *	into 8 bit bytes, left to right, for example:
 *		bbbaaaaa
 *		dcccccbb
 *		eeeedddd
 *		...
 *	We use a byte buffer read from the file and a sliding window to unpack
 *	the bytes.  Thanks to ImageMagick for the sliding window idea.
 *	args:  chan	    the channel to read from
 *	       code_size    size of the code to extract
 *	       flag	    boolean indicating whether the extractor should be
 *			    reset or not
 *
 * Results:
 *	code		    the next compression code
 *
 * Side effects:
 *	May consume more input from chan.
 *
 *----------------------------------------------------------------------
 */

static int
GetCode(chan, code_size, flag, gifConfPtr)
    Tcl_Channel chan;
    int code_size;
    int flag;
    GIFImageConfig *gifConfPtr;
{
    int ret;
    
    if (flag) {
	/*
	 * Initialize the decoder.
	 */
	gifConfPtr->reader.bitsInWindow = 0;
	gifConfPtr->reader.bytes = 0;
	gifConfPtr->reader.window = 0;
	gifConfPtr->reader.done = 0;
	gifConfPtr->reader.c = NULL;
	return 0;
    }

    while (gifConfPtr->reader.bitsInWindow < code_size) {
	/*
	 * Not enough bits in our window to cover the request.
	 */
	if (gifConfPtr->reader.done) {
	    return -1;
	}
	if (gifConfPtr->reader.bytes == 0) {
	    /*
	     * Not enough bytes in our buffer to add to the window.
	     */
	    gifConfPtr->reader.bytes =
		    GetDataBlock(gifConfPtr, chan, gifConfPtr->workingBuffer);
	    gifConfPtr->reader.c = gifConfPtr->reader.workingBuffer;
	    if (gifConfPtr->reader.bytes <= 0) {
		gifConfPtr->reader.done = 1;
		break;
	    }
	}
	/*
	 * Tack another byte onto the window, see if that's enough.
	 */
	gifConfPtr->reader.window +=
		(*gifConfPtr->reader.c) << gifConfPtr->reader.bitsInWindow;
	gifConfPtr->reader.c++;
	gifConfPtr->reader.bitsInWindow += 8;
	gifConfPtr->reader.bytes--;
    }

    /*
     * The next code will always be the last code_size bits of the window.
     */
    ret = gifConfPtr->reader.window & ((1 << code_size) - 1);
    
    /*
     * Shift data in the window to put the next code at the end.
     */
    gifConfPtr->reader.window >>= code_size;
    gifConfPtr->reader.bitsInWindow -= code_size;
    return ret;
}

/*
 *----------------------------------------------------------------------
 *
 * Minit -- --
 *
 *	This procedure initializes a base64 decoder handle
 *
 * Results:
 *	None
 *
 * Side effects:
 *	The base64 handle is initialized
 *
 *----------------------------------------------------------------------
 */

static void
mInit(string, handle, length)
   unsigned char *string;	/* string containing initial mmencoded data */
   MFile *handle;		/* mmdecode "file" handle */
   int length;			/* Number of bytes in string */
{
   handle->data = string;
   handle->state = 0;
   handle->c = 0;
   handle->length = length;
}

/*
 *----------------------------------------------------------------------
 *
 * Mread --
 *
 *	This procedure is invoked by the GIF file reader as a temporary
 *	replacement for "fread", to get GIF data out of a string (using
 *	Mgetc).
 *
 * Results:
 *	The return value is the number of characters "read"
 *
 * Side effects:
 *	The base64 handle will change state.
 *
 *----------------------------------------------------------------------
 */

static int
Mread(dst, chunkSize, numChunks, handle)  
   unsigned char *dst;	/* where to put the result */
   size_t chunkSize;	/* size of each transfer */
   size_t numChunks;	/* number of chunks */
   MFile *handle;	/* mmdecode "file" handle */
{
   register int i, c;
   int count = chunkSize * numChunks;

   for (i=0; i<count && (c=Mgetc(handle)) != GIF_DONE; i++) {
       *dst++ = c;
   }
   return i;
}

/*
 * Get the next decoded character from an mmencode handle.
 * This causes at least 1 character to be "read" from the encoded string
 */

/*
 *----------------------------------------------------------------------
 *
 * Mgetc --
 *
 *	This procedure decodes and returns the next byte from a base64 encoded
 *	string.
 *
 * Results:
 *	The next byte (or GIF_DONE) is returned.
 *
 * Side effects:
 *	The base64 handle will change state.
 *
 *----------------------------------------------------------------------
 */

static int
Mgetc(handle)
    MFile *handle;		/* Handle containing decoder data and state */
{
    int c;
    int result = 0;		/* Initialization needed only to prevent gcc
				 * compiler warning. */

    if (handle->state == GIF_DONE) {
	return GIF_DONE;
    }

    do {
	if (handle->length-- <= 0) {
	    return GIF_DONE;
	}
	c = char64(*handle->data);
	handle->data++;
    } while (c == GIF_SPACE);

    if (c>GIF_SPECIAL) {
	handle->state = GIF_DONE;
	return handle->c;
    }

    switch (handle->state++) {
    case 0:
	handle->c = c<<2;
	result = Mgetc(handle);
	break;
    case 1:
	result = handle->c | (c>>4);
	handle->c = (c&0xF)<<4;
	break;
    case 2:
	result = handle->c | (c>>2);
	handle->c = (c&0x3) << 6;
	break;
    case 3:
	result = handle->c | c;
	handle->state = 0;
	break;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * char64 --
 *
 *	This procedure converts a base64 ascii character into its binary
 *	equivalent.  This code is a slightly modified version of the char64
 *	proc in N. Borenstein's metamail decoder.
 *
 * Results:
 *	The binary value, or an error code.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
char64(c)
    int c;
{
    switch(c) {
    case 'A': return 0;  case 'B': return 1;  case 'C': return 2;
    case 'D': return 3;  case 'E': return 4;  case 'F': return 5;
    case 'G': return 6;  case 'H': return 7;  case 'I': return 8;
    case 'J': return 9;  case 'K': return 10; case 'L': return 11;
    case 'M': return 12; case 'N': return 13; case 'O': return 14;
    case 'P': return 15; case 'Q': return 16; case 'R': return 17;
    case 'S': return 18; case 'T': return 19; case 'U': return 20;
    case 'V': return 21; case 'W': return 22; case 'X': return 23;
    case 'Y': return 24; case 'Z': return 25; case 'a': return 26;
    case 'b': return 27; case 'c': return 28; case 'd': return 29;
    case 'e': return 30; case 'f': return 31; case 'g': return 32;
    case 'h': return 33; case 'i': return 34; case 'j': return 35;
    case 'k': return 36; case 'l': return 37; case 'm': return 38;
    case 'n': return 39; case 'o': return 40; case 'p': return 41;
    case 'q': return 42; case 'r': return 43; case 's': return 44;
    case 't': return 45; case 'u': return 46; case 'v': return 47;
    case 'w': return 48; case 'x': return 49; case 'y': return 50;
    case 'z': return 51; case '0': return 52; case '1': return 53;
    case '2': return 54; case '3': return 55; case '4': return 56;
    case '5': return 57; case '6': return 58; case '7': return 59;
    case '8': return 60; case '9': return 61; case '+': return 62;
    case '/': return 63;

    case ' ': case '\t': case '\n': case '\r': case '\f':
	return GIF_SPACE;
    case '=':
	return GIF_PAD;
    case '\0':
	return GIF_DONE;
    default:
	return GIF_BAD;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Fread --
 *
 *	This procedure calls either fread or Mread to read data from a file or
 *	a base64 encoded string.
 *
 * Results: - same as POSIX fread() or Tcl Tcl_Read()
 *
 *----------------------------------------------------------------------
 */

static int
Fread(gifConfPtr, dst, hunk, count, chan)
    GIFImageConfig *gifConfPtr;
    unsigned char *dst;		/* where to put the result */
    size_t hunk, count;		/* how many */
    Tcl_Channel chan;
{
    MFile *handle;

    if (gifConfPtr->fromData == INLINE_DATA_BASE64) {
	return Mread(dst, hunk, count, (MFile *) chan);
    }

    if (gifConfPtr->fromData == INLINE_DATA_BINARY) {
	handle = (MFile *) chan;
	if (handle->length <= 0 || (size_t)handle->length < hunk*count) {
	    return -1;
	}
	memcpy((VOID *)dst, (VOID *) handle->data, (size_t) (hunk * count));
	handle->data += hunk * count;
	return (int)(hunk * count);
    }

    /*
     * Otherwise we've got a real file to read.
     */
    return Tcl_Read(chan, (char *) dst, (int) (hunk * count));
}

/*
 * ChanWriteGIF - writes a image in GIF format.
 *-------------------------------------------------------------------------
 * Author:			Lolo
 *				Engeneering Projects Area 
 *				Department of Mining 
 *				University of Oviedo
 * e-mail			zz11425958@zeus.etsimo.uniovi.es
 *				lolo@pcsig22.etsimo.uniovi.es
 * Date:			Fri September 20 1996
 *
 * Modified for transparency handling (gif89a) and miGIF compression
 * by Jan Nijtmans <j.nijtmans@chello.nl>
 *
 *----------------------------------------------------------------------
 * FileWriteGIF-
 *
 *	This procedure is called by the photo image type to write GIF format
 *	data from a photo image into a given file
 *
 * Results:
 *	A standard TCL completion code.  If TCL_ERROR is returned then an
 *	error message is left in interp->result.
 *
 *----------------------------------------------------------------------
 */

/*
 * Types, defines and variables needed to write and compress a GIF.
 */

typedef int (* ifunptr) _ANSI_ARGS_((ClientData clientData));

#define LSB(a)			((unsigned char) (((short)(a)) & 0x00FF))
#define MSB(a)			((unsigned char) (((short)(a)) >> 8))

#define GIFBITS 12
#define HSIZE  5003		/* 80% occupancy */

typedef struct {
    int ssize;
    int csize;
    int rsize;
    unsigned char *pixelo;
    int pixelSize;
    int pixelPitch;
    int greenOffset;
    int blueOffset;
    int alphaOffset;
    int num;
    unsigned char mapa[MAXCOLORMAPSIZE][3];
} GifWriterState;

/*
 * Definition of new functions to write GIFs
 */

static int	color _ANSI_ARGS_((GifWriterState *statePtr,
		    int red, int green, int blue,
		    unsigned char mapa[MAXCOLORMAPSIZE][3]));
static void	compress _ANSI_ARGS_((int initBits, Tcl_Channel handle,
		    ifunptr readValue, ClientData clientData));
static int	nuevo _ANSI_ARGS_((GifWriterState *statePtr,
		    int red, int green, int blue,
		    unsigned char mapa[MAXCOLORMAPSIZE][3]));
static void	savemap _ANSI_ARGS_((GifWriterState *statePtr,
		    Tk_PhotoImageBlock *blockPtr,
		    unsigned char mapa[MAXCOLORMAPSIZE][3]));
static int	ReadValue _ANSI_ARGS_((ClientData clientData));

static int
FileWriteGIF(interp, filename, format, blockPtr)
    Tcl_Interp *interp;		/* Interpreter to use for reporting errors. */
    CONST char	*filename;
    Tcl_Obj	*format;
    Tk_PhotoImageBlock *blockPtr;
{
    Tcl_Channel chan = NULL;
    int result;

    chan = Tcl_OpenFileChannel(interp, (char *) filename, "w", 0644);
    if (!chan) {
	return TCL_ERROR;
    }
    if (Tcl_SetChannelOption(interp, chan, "-translation",
	    "binary") != TCL_OK) {
	Tcl_Close(NULL, chan);
	return TCL_ERROR;
    }

    result = CommonWriteGIF(interp, chan, format, blockPtr);

    if (Tcl_Close(interp, chan) == TCL_ERROR) {
	return TCL_ERROR;
    }
    return result;
}

static int
CommonWriteGIF(interp, handle, format, blockPtr)
    Tcl_Interp *interp;
    Tcl_Channel handle;
    Tcl_Obj *format;
    Tk_PhotoImageBlock *blockPtr;
{
    GifWriteState state, *statePtr = &state;
    int resolution;
    long width, height, x;
    unsigned char c;
    unsigned int top, left;

    top = 0;
    left = 0;

    memset(statePtr, 0, sizeof(state));

    statePtr->pixelSize = blockPtr->pixelSize;
    statePtr->greenOffset = blockPtr->offset[1]-blockPtr->offset[0];
    statePtr->blueOffset = blockPtr->offset[2]-blockPtr->offset[0];
    statePtr->alphaOffset = blockPtr->offset[0];
    if (statePtr->alphaOffset < blockPtr->offset[2]) {
	statePtr->alphaOffset = blockPtr->offset[2];
    }
    if (++statePtr->alphaOffset < statePtr->pixelSize) {
	statePtr->alphaOffset -= blockPtr->offset[0];
    } else {
	statePtr->alphaOffset = 0;
    }

    Tcl_Write(handle, (char *) (statePtr->alphaOffset ? GIF89a : GIF87a), 6);

    for (x=0 ; x<MAXCOLORMAPSIZE ; x++) {
	statePtr->mapa[x][CM_RED] = 255;
	statePtr->mapa[x][CM_GREEN] = 255;
	statePtr->mapa[x][CM_BLUE] = 255;
    }


    width = blockPtr->width;
    height = blockPtr->height;
    statePtr->pixelo = blockPtr->pixelPtr + blockPtr->offset[0];
    statePtr->pixelPitch = blockPtr->pitch;
    savemap(statePtr, blockPtr, statePtr->mapa);
    if (statePtr->num >= MAXCOLORMAPSIZE) {
	Tcl_AppendResult(interp, "too many colors", (char *) NULL);
	return TCL_ERROR;
    }
    if (statePtr->num<2) {
	statePtr->num = 2;
    }
    c = LSB(width);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(width);
    Tcl_Write(handle, (char *) &c, 1);
    c = LSB(height);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(height);
    Tcl_Write(handle, (char *) &c, 1);

    resolution = 0;
    while (statePtr->num >> resolution) {
	resolution++;
    }
    c = 111 + resolution * 17;
    Tcl_Write(handle, (char *) &c, 1);

    statePtr->num = 1 << resolution;

    /*
     * background color
     */

    c = 0;
    Tcl_Write(handle, (char *) &c, 1);

    /*
     * zero for future expansion.
     */

    Tcl_Write(handle, (char *) &c, 1);

    for (x=0 ; x<statePtr->num ; x++) {
	c = statePtr->mapa[x][CM_RED];
	Tcl_Write(handle, (char *) &c, 1);
	c = statePtr->mapa[x][CM_GREEN];
	Tcl_Write(handle, (char *) &c, 1);
	c = statePtr->mapa[x][CM_BLUE];
	Tcl_Write(handle, (char *) &c, 1);
    }

    /*
     * Write out extension for transparent colour index, if necessary.
     */

    if (statePtr->alphaOffset) {
	c = GIF_EXTENSION;
	Tcl_Write(handle, (char *) &c, 1);
	Tcl_Write(handle, "\371\4\1\0\0\0", 7);
    }

    c = GIF_START;
    Tcl_Write(handle, (char *) &c, 1);
    c = LSB(top);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(top);
    Tcl_Write(handle, (char *) &c, 1);
    c = LSB(left);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(left);
    Tcl_Write(handle, (char *) &c, 1);

    c = LSB(width);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(width);
    Tcl_Write(handle, (char *) &c, 1);

    c = LSB(height);
    Tcl_Write(handle, (char *) &c, 1);
    c = MSB(height);
    Tcl_Write(handle, (char *) &c, 1);

    c = 0;
    Tcl_Write(handle, (char *) &c, 1);
    c = resolution;
    Tcl_Write(handle, (char *) &c, 1);

    statePtr->ssize = statePtr->rsize = blockPtr->width;
    statePtr->csize = blockPtr->height;
    compress(resolution+1, handle, ReadValue, (ClientData) statePtr);

    c = 0; 
    Tcl_Write(handle, (char *) &c, 1);
    c = GIF_TERMINATOR;
    Tcl_Write(handle, (char *) &c, 1);

    return TCL_OK;	
}

static int
color(statePtr, red, green, blue, mapa)
    GifWriterState *statePtr;
    int red;
    int green;
    int blue;
    unsigned char mapa[MAXCOLORMAPSIZE][3];
{
    int x;
    for (x=(statePtr->alphaOffset != 0) ; x<=MAXCOLORMAPSIZE ; x++) {
	if ((mapa[x][CM_RED] == red) && (mapa[x][CM_GREEN] == green) &&
		(mapa[x][CM_BLUE] == blue)) {
	    return x;
	}
    }
    return -1;
}

static int
nuevo(statePtr, red, green, blue, mapa)
    GifWriterState *statePtr;
    int red, green, blue;
    unsigned char mapa[MAXCOLORMAPSIZE][3];
{
    int x = (statePtr->alphaOffset != 0);
    for (; x<=statePtr->num ; x++) {
	if ((mapa[x][CM_RED] == red) && (mapa[x][CM_GREEN] == green) &&
		(mapa[x][CM_BLUE] == blue)) {
	    return 0;
	}
    }
    return 1;
}

static void
savemap(statePtr, blockPtr, mapa)
    GifWriterState *statePtr;
    Tk_PhotoImageBlock *blockPtr;
    unsigned char mapa[MAXCOLORMAPSIZE][3];
{
    unsigned char *colores;
    int x, y;
    unsigned char red, green, blue;

    if (statePtr->alphaOffset) {
	statePtr->num = 0;
	mapa[0][CM_RED] = 0xd9;
	mapa[0][CM_GREEN] = 0xd9;
	mapa[0][CM_BLUE] = 0xd9;
    } else {
	statePtr->num = -1;
    }

    for(y=0 ; y<blockPtr->height ; y++) {
	colores = blockPtr->pixelPtr + blockPtr->offset[0] + y*blockPtr->pitch;
	for(x=0 ; x<blockPtr->width ; x++) {
	    if (!statePtr->alphaOffset || colores[statePtr->alphaOffset]!=0) {
		red = colores[0];
		green = colores[statePtr->greenOffset];
		blue = colores[statePtr->blueOffset];
		if (nuevo(statePtr, red, green, blue, mapa)) {
		    statePtr->num++;
		    if (statePtr->num >= MAXCOLORMAPSIZE) {
			return;
		    }
		    mapa[statePtr->num][CM_RED] = red;
		    mapa[statePtr->num][CM_GREEN] = green;
		    mapa[statePtr->num][CM_BLUE] = blue;
		}
	    }
	    colores += statePtr->pixelSize;
	}
    }
    return;
}

static int
ReadValue(clientData)
    ClientData clientData;
{
    GifWriterState *statePtr = (GifWriterState *) clientData;
    unsigned int col;

    if (statePtr->csize == 0) {
	return EOF;
    }
    if (statePtr->alphaOffset && statePtr->pixelo[statePtr->alphaOffset]==0) {
	col = 0;
    } else {
	col = color(statePtr, statePtr->pixelo[0],
		statePtr->pixelo[statePtr->greenOffset],
		statePtr->pixelo[statePtr->blueOffset], statePtr->mapa);
    }
    statePtr->pixelo += statePtr->pixelSize;
    if (--statePtr->ssize <= 0) {
	statePtr->ssize = statePtr->rsize;
	statePtr->csize--;
	statePtr->pixelo += statePtr->pixelPitch
		- (statePtr->rsize * statePtr->pixelSize);
    }

    return col;
}

/*
 *-----------------------------------------------------------------------
 *
 * miGIF Compression - mouse and ivo's GIF-compatible compression
 *
 *		-run length encoding compression routines-
 *
 * Copyright (C) 1998 Hutchison Avenue Software Corporation
 *		 http://www.hasc.com
 *		 info@hasc.com
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation. This software is provided "AS IS." The Hutchison Avenue
 * Software Corporation disclaims all warranties, either express or implied,
 * including but not limited to implied warranties of merchantability and
 * fitness for a particular purpose, with respect to this code and
 * accompanying documentation.
 * 
 * The miGIF compression routines do not, strictly speaking, generate files
 * conforming to the GIF spec, since the image data is not LZW-compressed
 * (this is the point: in order to avoid transgression of the Unisys patent on
 * the LZW algorithm.) However, miGIF generates data streams that any
 * reasonably sane LZW decompresser will decompress to what we want.
 *
 * miGIF compression uses run length encoding. It compresses horizontal runs
 * of pixels of the same color. This type of compression gives good results on
 * images with many runs, for example images with lines, text and solid shapes
 * on a solid-colored background. It gives little or no compression on images
 * with few runs, for example digital or scanned photos.
 *
 *				 der Mouse
 *			mouse@rodents.montreal.qc.ca
 *	      7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B
 *
 *			       ivo@hasc.com
 *
 * The Graphics Interchange Format(c) is the Copyright property of CompuServe
 * Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated.
 *
 *-----------------------------------------------------------------------
 */

typedef struct {
    int runlengthPixel;
    int runlengthBaseCode;
    int runlengthCount;
    int runlengthTablePixel;
    int runlengthTableMax;
    int justCleared;
    int outputBits;
    int outputBitsInit;
    int outputCount;
    int outputBump;
    int outputBumpInit;
    int outputClear;
    int outputClearInit;
    int maxOcodes;
    int codeClear;
    int codeEOF;
    unsigned int obuf;
    int obits;
    Tcl_Channel ofile;
    unsigned char oblock[256];
    int oblen;
} miGIFState_t;

/*
 * Used only when debugging GIF compression code
 */
/* #define MIGIF_DEBUGGING_ENVARS */

#ifdef MIGIF_DEBUGGING_ENVARS

/*
 * This debugging code is _absolutely_ not thread-safe. It's also not normally
 * enabled either.
 */

static int verboseSet = 0;
static int verbose;
#define MIGIF_VERBOSE (verboseSet?verbose:setVerbose())
#define DEBUGMSG(printfArgs) if (MIGIF_VERBOSE) { printf printfArgs; }

static int
setVerbose(void)
{
    verbose = !!getenv("MIGIF_VERBOSE");
    verboseSet = 1;
    return verbose;
}

static const char *
binformat(v, nbits)
    unsigned int v;
    int nbits;
{
    static char bufs[8][64];
    static int bhand = 0;
    unsigned int bit;
    int bno;
    char *bp;

    bhand--;
    if (bhand < 0) {
	bhand = (sizeof(bufs) / sizeof(bufs[0])) - 1;
    }
    bp = &bufs[bhand][0];
    for (bno=nbits-1,bit=((unsigned int)1)<<bno ; bno>=0 ; bno--,bit>>=1) {
	*bp++ = (v & bit) ? '1' : '0';
	if (((bno&3) == 0) && (bno != 0)) {
	    *bp++ = '.';
	}
    }
    *bp = '\0';
    return &bufs[bhand][0];
}
#else /* !MIGIF_DEBUGGING_ENVARS */
#define DEBUGMSG(printfArgs) /* do nothing */
#endif

static void
writeBlock(statePtr)
    miGIFState_t *statePtr;
{
    int i;
    unsigned char c;

#ifdef MIGIF_DEBUGGING_ENVARS
    if (MIGIF_VERBOSE) {
	printf("writeBlock %d:", statePtr->oblen);
	for (i=0 ; i<statePtr->oblen ; i++) {
	    printf(" %02x", statePtr->oblock[i]);
	}
	printf("\n");
    }
#endif
    c = statePtr->oblen;
    Tcl_Write(statePtr->ofile, (char *) &c, 1);
    Tcl_Write(statePtr->ofile, (char *) &statePtr->oblock[0], statePtr->oblen);
    statePtr->oblen = 0;
}

static void
blockOut(statePtr, c)
    miGIFState_t *statePtr;
    unsigned char c;
{
    DEBUGMSG(("blockOut %s\n", binformat(c, 8)));
    statePtr->oblock[statePtr->oblen++] = c;
    if (statePtr->oblen >= 255) {
	writeBlock(statePtr);
    }
}

static void
blockFlush(statePtr)
    miGIFState_t *statePtr;
{
    DEBUGMSG(("blockFlush\n"));
    if (statePtr->oblen > 0) {
	writeBlock(statePtr);
    }
}

static void
output(statePtr, val)
    miGIFState_t *statePtr;
    int val;
{
    DEBUGMSG(("output %s [%s %d %d]\n", binformat(val, statePtr->outputBits),
	    binformat(statePtr->obuf, statePtr->obits), statePtr->obits,
	    statePtr->outputBits));
    statePtr->obuf |= val << statePtr->obits;
    statePtr->obits += statePtr->outputBits;
    while (statePtr->obits >= 8) {
	blockOut(statePtr, statePtr->obuf&0xff);
	statePtr->obuf >>= 8;
	statePtr->obits -= 8;
    }
    DEBUGMSG(("output leaving [%s %d]\n",
	    binformat(statePtr->obuf, statePtr->obits), statePtr->obits));
}

static void
outputFlush(statePtr)
    miGIFState_t *statePtr;
{
    DEBUGMSG(("outputFlush\n"));
    if (statePtr->obits > 0) {
	blockOut(statePtr, statePtr->obuf);
    }
    blockFlush(statePtr);
}

static void
didClear(statePtr)
    miGIFState_t *statePtr;
{
    DEBUGMSG(("didClear\n"));
    statePtr->outputBits = statePtr->outputBitsInit;
    statePtr->outputBump = statePtr->outputBumpInit;
    statePtr->outputClear = statePtr->outputClearInit;
    statePtr->outputCount = 0;
    statePtr->runlengthTableMax = 0;
    statePtr->justCleared = 1;
}

static void
outputPlain(statePtr, c)
    miGIFState_t *statePtr;
    int c;
{
    DEBUGMSG(("outputPlain %s\n", binformat(c, statePtr->outputBits)));
    statePtr->justCleared = 0;
    output(statePtr, c);
    statePtr->outputCount++;
    if (statePtr->outputCount >= statePtr->outputBump) {
	statePtr->outputBits++;
	statePtr->outputBump += 1 << (statePtr->outputBits - 1);
    }
    if (statePtr->outputCount >= statePtr->outputClear) {
	output(statePtr, statePtr->codeClear);
	didClear(statePtr);
    }
}

static unsigned int
isqrt(x)
    unsigned int x;
{
    unsigned int r;
    unsigned int v;

    if (x < 2) {
	return x;
    }
    for (v=x,r=1 ; v ; v>>=2,r<<=1);
    while (1) {
	v = ((x / r) + r) / 2;
	if (v==r || v==r+1) {
	    return r;
	}
	r = v;
    }
}

static unsigned int
computeTriangleCount(count, nrepcodes)
    unsigned int count;
    unsigned int nrepcodes;
{
    unsigned int perrep;
    unsigned int cost;

    cost = 0;
    perrep = (nrepcodes * (nrepcodes+1)) / 2;
    while (count >= perrep) {
	cost += nrepcodes;
	count -= perrep;
    }
    if (count > 0) {
	unsigned int n;
	n = isqrt(count);
	while (n*(n+1) >= 2*count) {
	    n--;
	}
	while (n*(n+1) < 2*count) {
	    n++;
	}
	cost += n;
    }
    return cost;
}

static void
maxOutputClear(statePtr)
    miGIFState_t *statePtr;
{
    statePtr->outputClear = statePtr->maxOcodes;
}

static void
resetOutputClear(statePtr)
    miGIFState_t *statePtr;
{
    statePtr->outputClear = statePtr->outputClearInit;
    if (statePtr->outputCount >= statePtr->outputClear) {
	output(statePtr, statePtr->codeClear);
	didClear(statePtr);
    }
}

static void
runlengthFlushFromClear(statePtr, count)
    miGIFState_t *statePtr;
    int count;
{
    int n;

    DEBUGMSG(("runlengthFlushFromClear %d\n", count));
    maxOutputClear(statePtr);
    statePtr->runlengthTablePixel = statePtr->runlengthPixel;
    n = 1;
    while (count > 0) {
	if (n == 1) {
	    statePtr->runlengthTableMax = 1;
	    outputPlain(statePtr, statePtr->runlengthPixel);
	    count--;
	} else if (count >= n) {
	    statePtr->runlengthTableMax = n;
	    outputPlain(statePtr, statePtr->runlengthBaseCode+n-2);
	    count -= n;
	} else if (count == 1) {
	    statePtr->runlengthTableMax++;
	    outputPlain(statePtr, statePtr->runlengthPixel);
	    count = 0;
	} else {
	    statePtr->runlengthTableMax++;
	    outputPlain(statePtr, statePtr->runlengthBaseCode+count-2);
	    count = 0;
	}
	if (statePtr->outputCount == 0) {
	    n = 1;
	} else {
	    n++;
	}
    }
    resetOutputClear(statePtr);
    DEBUGMSG(("runlengthFlushFromClear leaving tableMax=%d\n",
	    statePtr->runlengthTableMax));
}

static void
runlengthFlushClearOrRep(statePtr, count)
    miGIFState_t *statePtr;
    int count;
{
    int withclr;

    DEBUGMSG(("runlengthFlushClearOrRep %d\n", count));
    withclr = 1 + computeTriangleCount(count, statePtr->maxOcodes);
    if (withclr < count) {
	output(statePtr, statePtr->codeClear);
	didClear(statePtr);
	runlengthFlushFromClear(statePtr, count);
    } else {
	for (; count>0 ; count--) {
	    outputPlain(statePtr, statePtr->runlengthPixel);
	}
    }
}

static void
runlengthFlushWithTable(statePtr, count)
    miGIFState_t *statePtr;
    int count;
{
    int repmax;
    int repleft;
    int leftover;

    DEBUGMSG(("runlengthFlushWithTable %d\n", count));
    repmax = count / statePtr->runlengthTableMax;
    leftover = count % statePtr->runlengthTableMax;
    repleft = (leftover ? 1 : 0);
    if (statePtr->outputCount+repmax+repleft > statePtr->maxOcodes) {
	repmax = statePtr->maxOcodes - statePtr->outputCount;
	leftover = count - (repmax * statePtr->runlengthTableMax);
	repleft = 1 + computeTriangleCount(leftover, statePtr->maxOcodes);
    }
    DEBUGMSG(("runlengthFlushWithTable repmax=%d leftover=%d repleft=%d\n",
	    repmax, leftover, repleft));
    if (1+(int)computeTriangleCount(count, statePtr->maxOcodes)
	    < repmax+repleft) {
	output(statePtr, statePtr->codeClear);
	didClear(statePtr);
	runlengthFlushFromClear(statePtr, count);
	return;
    }
    maxOutputClear(statePtr);
    for (; repmax>0 ; repmax--) {
	outputPlain(statPtr,
		statePtr->runlengthBaseCode + statePtr->runlengthTableMax - 2);
    }
    if (leftover) {
	if (statePtr->justCleared) {
	    runlengthFlushFromClear(statePtr, leftover);
	} else if (leftover == 1) {
	    outputPlain(statePtr, statePtr->runlengthPixel);
	} else {
	    outputPlain(statePtr, statePtr->runlengthBaseCode + leftover - 2);
	}
    }
    resetOutputClear(statePtr);
}

static void
runlengthFlush(statePtr)
    miGIFState_t *statePtr;
{
    DEBUGMSG(("runlengthFlush [ %d %d\n", statePtr->runlengthCount,
	    statePtr->runlengthPixel));
    if (statePtr->runlengthCount == 1) {
	outputPlain(statePtr, statePtr->runlengthPixel);
	statePtr->runlengthCount = 0;
	DEBUGMSG(("runlengthFlush ]\n"));
	return;
    }
    if (statePtr->justCleared) {
	runlengthFlushFromClear(statePtr, statePtr->runlengthCount);
    } else if ((statePtr->runlengthTableMax < 2)
	    || (statePtr->runlengthTablePixel != statePtr->runlengthPixel)) {
	runlengthFlushClearOrRep(statePtr, statePtr->runlengthCount);
    } else {
	runlengthFlushWithTable(statePtr, statePtr->runlengthCount);
    }
    DEBUGMSG(("runlengthFlush ]\n"));
    statePtr->runlengthCount = 0;
}

static void
compress(initBits, handle, readValue, clientData)
    int initBits;
    Tcl_Channel handle;
    ifunptr readValue;
    ClientData clientData;
{
    int c;
    miGIFState_t state, *statePtr = &state;

    memset(statePtr, 0, sizeof(state));

    statePtr->ofile = handle;
    statePtr->obuf = 0;
    statePtr->obits = 0;
    statePtr->oblen = 0;
    statePtr->codeClear = 1 << (initBits - 1);
    statePtr->codeEOF = statePtr->codeClear + 1;
    statePtr->runlengthBaseCode = statePtr->codeEOF + 1;
    statePtr->outputBumpInit = (1 << (initBits - 1)) - 1;
    /*
     * For images with a lot of runs, making outputClearInit larger will give
     * better compression.
     */
    statePtr->outputClearInit =
	    (initBits <= 3) ? 9 : (statePtr->outputBumpInit-1);
#ifdef MIGIF_DEBUGGING_ENVARS
    {
	const char *ocienv;
	ocienv = getenv("MIGIF_OUT_CLEAR_INIT");
	if (ocienv) {
	    statePtr->outputClearInit = atoi(ocienv);
	    DEBUGMSG(("[overriding outputClearInit to %d]\n",
		    statePtr->outputClearInit));
	}
    }
#endif
    statePtr->outputBitsInit = initBits;
    statePtr->maxOcodes =
	    (1 << GIFBITS) - ((1 << (statePtr->outputBitsInit - 1)) + 3);
    didClear(statePtr);
    output(statePtr, statePtr->codeClear);
    statePtr->runlengthCount = 0;
    while (1) {
	c = readValue(clientData);
	if (statePtr->runlengthCount>0 && statePtr->runlengthPixel!=c) {
	    runlengthFlush(statePtr);
	}
	if (c == EOF) {
	    break;
	}
	if (statePtr->runlengthPixel == c) {
	    statePtr->runlengthCount++;
	} else {
	    statePtr->runlengthPixel = c;
	    statePtr->runlengthCount = 1;
	}
    }
    output(statePtr, statePtr->codeEOF);
    outputFlush(statePtr);
}

/*
 *-----------------------------------------------------------------------
 *
 * End of miGIF section  - See copyright notice at start of section.
 *
 *-----------------------------------------------------------------------
 */