summaryrefslogtreecommitdiff
path: root/Build/source/libs/libpng/libpng-1.2.38/contrib/gregbook/rpng2-x.c
blob: 873af2335432694120f4470871efa8d1d597fbe6 (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
/*---------------------------------------------------------------------------

   rpng2 - progressive-model PNG display program                  rpng2-x.c

   This program decodes and displays PNG files progressively, as if it were
   a web browser (though the front end is only set up to read from files).
   It supports gamma correction, user-specified background colors, and user-
   specified background patterns (for transparent images).  This version is
   for the X Window System (tested by the author under Unix and by Martin
   Zinser under OpenVMS; may work under OS/2 with a little tweaking).

   Thanks to Adam Costello and Pieter S. van der Meulen for the "diamond"
   and "radial waves" patterns, respectively.

   to do (someday, maybe):
    - fix expose/redraw code:  don't draw entire row if only part exposed
    - 8-bit (colormapped) X support
    - finish resizable checkerboard-gradient (sizes 4-128?)
    - use %.1023s to simplify truncation of title-bar string?

  ---------------------------------------------------------------------------

   Changelog:
    - 1.01:  initial public release
    - 1.02:  modified to allow abbreviated options; fixed char/uchar mismatch
    - 1.10:  added support for non-default visuals; fixed X pixel-conversion
    - 1.11:  added -usleep option for demos; fixed command-line parsing bug
    - 1.12:  added -pause option for demos and testing
    - 1.20:  added runtime MMX-enabling/disabling and new -mmx* options
    - 1.21:  fixed some small X memory leaks (thanks to François Petitjean)
    - 1.22:  fixed XFreeGC() crash bug (thanks to Patrick Welche)
    - 1.23:  added -bgpat 0 mode (std white/gray checkerboard, 8x8 squares)
    - 1.30:  added -loop option for -bgpat (ifdef FEATURE_LOOP); fixed bpp =
              24; added support for X resources (thanks to Gerhard Niklasch)
    - 1.31:  added code to skip unused chunks (thanks to Glenn Randers-Pehrson)
    - 1.32:  added AMD64/EM64T support (__x86_64__); added basic expose/redraw
              handling
    - 2.00:  dual-licensed (added GNU GPL)
    - 2.01:  fixed 64-bit typo in readpng2.c; fixed -pause usage description
    - 2.02:  fixed improper display of usage screen on PNG error(s); fixed
              unexpected-EOF and file-read-error cases; fixed Trace() cut-and-
              paste bugs

  ---------------------------------------------------------------------------

      Copyright (c) 1998-2008 Greg Roelofs.  All rights reserved.

      This software is provided "as is," without warranty of any kind,
      express or implied.  In no event shall the author or contributors
      be held liable for any damages arising in any way from the use of
      this software.

      The contents of this file are DUAL-LICENSED.  You may modify and/or
      redistribute this software according to the terms of one of the
      following two licenses (at your option):


      LICENSE 1 ("BSD-like with advertising clause"):

      Permission is granted to anyone to use this software for any purpose,
      including commercial applications, and to alter it and redistribute
      it freely, subject to the following restrictions:

      1. Redistributions of source code must retain the above copyright
         notice, disclaimer, and this list of conditions.
      2. Redistributions in binary form must reproduce the above copyright
         notice, disclaimer, and this list of conditions in the documenta-
         tion and/or other materials provided with the distribution.
      3. All advertising materials mentioning features or use of this
         software must display the following acknowledgment:

            This product includes software developed by Greg Roelofs
            and contributors for the book, "PNG: The Definitive Guide,"
            published by O'Reilly and Associates.


      LICENSE 2 (GNU GPL v2 or later):

      This program is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation; either version 2 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software Foundation,
      Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  ---------------------------------------------------------------------------*/

#define PROGNAME  "rpng2-x"
#define LONGNAME  "Progressive PNG Viewer for X"
#define VERSION   "2.02 of 16 March 2008"
#define RESNAME   "rpng2"	/* our X resource application name */
#define RESCLASS  "Rpng"	/* our X resource class name */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <setjmp.h>       /* for jmpbuf declaration in readpng2.h */
#include <time.h>
#include <math.h>         /* only for PvdM background code */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/keysym.h>   /* defines XK_* macros */

#ifdef VMS
#  include <unistd.h>
#endif

/* all for PvdM background code: */
#ifndef PI
#  define PI             3.141592653589793238
#endif
#define PI_2             (PI*0.5)
#define INV_PI_360       (360.0 / PI)
#define MAX(a,b)         (a>b?a:b)
#define MIN(a,b)         (a<b?a:b)
#define CLIP(a,min,max)  MAX(min,MIN((a),max))
#define ABS(a)           ((a)<0?-(a):(a))
#define CLIP8P(c)        MAX(0,(MIN((c),255)))   /* 8-bit pos. integer (uch) */
#define ROUNDF(f)        ((int)(f + 0.5))

#define QUIT(e,k) ((e.type == ButtonPress && e.xbutton.button == Button1) ||  \
                  (e.type == KeyPress &&   /*  v--- or 1 for shifted keys */  \
                  ((k = XLookupKeysym(&e.xkey, 0)) == XK_q || k == XK_Escape)))

#define NO_24BIT_MASKS	/* undef case not fully written--only for redisplay() */

#define rgb1_max   bg_freq
#define rgb1_min   bg_gray
#define rgb2_max   bg_bsat
#define rgb2_min   bg_brot

/* #define DEBUG */     /* this enables the Trace() macros */

#include "readpng2.h"   /* typedefs, common macros, readpng2 prototypes */


/* could just include png.h, but this macro is the only thing we need
 * (name and typedefs changed to local versions); note that side effects
 * only happen with alpha (which could easily be avoided with
 * "ush acopy = (alpha);") */

#define alpha_composite(composite, fg, alpha, bg) {               \
    ush temp = ((ush)(fg)*(ush)(alpha) +                          \
                (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128);  \
    (composite) = (uch)((temp + (temp >> 8)) >> 8);               \
}


#define INBUFSIZE 4096   /* with pseudo-timing on (1 sec delay/block), this
                          *  block size corresponds roughly to a download
                          *  speed 10% faster than theoretical 33.6K maximum
                          *  (assuming 8 data bits, 1 stop bit and no other
                          *  overhead) */

/* local prototypes */
static void rpng2_x_init (void);
static int  rpng2_x_create_window (void);
static int  rpng2_x_load_bg_image (void);
static void rpng2_x_display_row (ulg row);
static void rpng2_x_finish_display (void);
static void rpng2_x_redisplay_image (ulg startcol, ulg startrow,
                                     ulg width, ulg height);
#ifdef FEATURE_LOOP
static void rpng2_x_reload_bg_image (void);
static int  is_number (char *p);
#endif
static void rpng2_x_cleanup (void);
static int  rpng2_x_msb (ulg u32val);


static char titlebar[1024], *window_name = titlebar;
static char *appname = LONGNAME;
static char *icon_name = PROGNAME;
static char *res_name = RESNAME;
static char *res_class = RESCLASS;
static char *filename;
static FILE *infile;

static mainprog_info rpng2_info;

static uch inbuf[INBUFSIZE];
static int incount;

static int pat = 6;        /* must be less than num_bgpat */
static int bg_image = 0;
static int bgscale, bgscale_default = 16;
static ulg bg_rowbytes;
static uch *bg_data;

int pause_after_pass = FALSE;
int demo_timing = FALSE;
ulg usleep_duration = 0L;

static struct rgb_color {
    uch r, g, b;
} rgb[] = {
    {  0,   0,   0},    /*  0:  black */
    {255, 255, 255},    /*  1:  white */
    {173, 132,  57},    /*  2:  tan */
    { 64, 132,   0},    /*  3:  medium green */
    {189, 117,   1},    /*  4:  gold */
    {253, 249,   1},    /*  5:  yellow */
    {  0,   0, 255},    /*  6:  blue */
    {  0,   0, 120},    /*  7:  medium blue */
    {255,   0, 255},    /*  8:  magenta */
    { 64,   0,  64},    /*  9:  dark magenta */
    {255,   0,   0},    /* 10:  red */
    { 64,   0,   0},    /* 11:  dark red */
    {255, 127,   0},    /* 12:  orange */
    {192,  96,   0},    /* 13:  darker orange */
    { 24,  60,   0},    /* 14:  dark green-yellow */
    { 85, 125, 200},    /* 15:  ice blue */
    {192, 192, 192}     /* 16:  Netscape/Mosaic gray */
};
/* not used for now, but should be for error-checking:
static int num_rgb = sizeof(rgb) / sizeof(struct rgb_color);
 */

/*
    This whole struct is a fairly cheesy way to keep the number of
    command-line options to a minimum.  The radial-waves background
    type is a particularly poor fit to the integer elements of the
    struct...but a few macros and a little fixed-point math will do
    wonders for ya.

    type bits:
       F E D C B A 9 8 7 6 5 4 3 2 1 0
                             | | | | |
                             | | +-+-+-- 0 = sharp-edged checkerboard
                             | |         1 = soft diamonds
                             | |         2 = radial waves
                             | |       3-7 = undefined
                             | +-- gradient #2 inverted?
                             +-- alternating columns inverted?
 */
static struct background_pattern {
    ush type;
    int rgb1_max, rgb1_min;     /* or bg_freq, bg_gray */
    int rgb2_max, rgb2_min;     /* or bg_bsat, bg_brot (both scaled by 10)*/
} bg[] = {
    {0,     1,1, 16,16},        /* checkered:  white vs. light gray (basic) */
    {0+8,   2,0,  1,15},        /* checkered:  tan/black vs. white/ice blue */
    {0+24,  2,0,  1,0},         /* checkered:  tan/black vs. white/black */
    {0+8,   4,5,  0,2},         /* checkered:  gold/yellow vs. black/tan */
    {0+8,   4,5,  0,6},         /* checkered:  gold/yellow vs. black/blue */
    {0,     7,0,  8,9},         /* checkered:  deep blue/black vs. magenta */
    {0+8,  13,0,  5,14},        /* checkered:  orange/black vs. yellow */
    {0+8,  12,0, 10,11},        /* checkered:  orange/black vs. red */
    {1,     7,0,  8,0},         /* diamonds:  deep blue/black vs. magenta */
    {1,    12,0, 11,0},         /* diamonds:  orange vs. dark red */
    {1,    10,0,  7,0},         /* diamonds:  red vs. medium blue */
    {1,     4,0,  5,0},         /* diamonds:  gold vs. yellow */
    {1,     3,0,  0,0},         /* diamonds:  medium green vs. black */
    {2,    16, 100,  20,   0},  /* radial:  ~hard radial color-beams */
    {2,    18, 100,  10,   2},  /* radial:  soft, curved radial color-beams */
    {2,    16, 256, 100, 250},  /* radial:  very tight spiral */
    {2, 10000, 256,  11,   0}   /* radial:  dipole-moire' (almost fractal) */
};
static int num_bgpat = sizeof(bg) / sizeof(struct background_pattern);


/* X-specific variables */
static char *displayname;
static XImage *ximage;
static Display *display;
static int depth;
static Visual *visual;
static XVisualInfo *visual_list;
static int RShift, GShift, BShift;
static ulg RMask, GMask, BMask;
static Window window;
static GC gc;
static Colormap colormap;

static int have_nondefault_visual = FALSE;
static int have_colormap = FALSE;
static int have_window = FALSE;
static int have_gc = FALSE;




int main(int argc, char **argv)
{
#ifdef sgi
    char tmpline[80];
#endif
    char *p, *bgstr = NULL;
    int rc, alen, flen;
    int error = 0;
    int timing = FALSE;
    int have_bg = FALSE;
#ifdef FEATURE_LOOP
    int loop = FALSE;
    long loop_interval = -1;		/* seconds (100,000 max) */
#endif
    double LUT_exponent;                /* just the lookup table */
    double CRT_exponent = 2.2;          /* just the monitor */
    double default_display_exponent;    /* whole display system */
    XEvent e;
    KeySym k;


    /* First initialize a few things, just to be sure--memset takes care of
     * default background color (black), booleans (FALSE), pointers (NULL),
     * etc. */

    displayname = (char *)NULL;
    filename = (char *)NULL;
    memset(&rpng2_info, 0, sizeof(mainprog_info));


    /* Set the default value for our display-system exponent, i.e., the
     * product of the CRT exponent and the exponent corresponding to
     * the frame-buffer's lookup table (LUT), if any.  This is not an
     * exhaustive list of LUT values (e.g., OpenStep has a lot of weird
     * ones), but it should cover 99% of the current possibilities. */

#if defined(NeXT)
    /* third-party utilities can modify the default LUT exponent */
    LUT_exponent = 1.0 / 2.2;
    /*
    if (some_next_function_that_returns_gamma(&next_gamma))
        LUT_exponent = 1.0 / next_gamma;
     */
#elif defined(sgi)
    LUT_exponent = 1.0 / 1.7;
    /* there doesn't seem to be any documented function to
     * get the "gamma" value, so we do it the hard way */
    infile = fopen("/etc/config/system.glGammaVal", "r");
    if (infile) {
        double sgi_gamma;

        fgets(tmpline, 80, infile);
        fclose(infile);
        sgi_gamma = atof(tmpline);
        if (sgi_gamma > 0.0)
            LUT_exponent = 1.0 / sgi_gamma;
    }
#elif defined(Macintosh)
    LUT_exponent = 1.8 / 2.61;
    /*
    if (some_mac_function_that_returns_gamma(&mac_gamma))
        LUT_exponent = mac_gamma / 2.61;
     */
#else
    LUT_exponent = 1.0;   /* assume no LUT:  most PCs */
#endif

    /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
    default_display_exponent = LUT_exponent * CRT_exponent;


    /* If the user has set the SCREEN_GAMMA environment variable as suggested
     * (somewhat imprecisely) in the libpng documentation, use that; otherwise
     * use the default value we just calculated.  Either way, the user may
     * override this via a command-line option. */

    if ((p = getenv("SCREEN_GAMMA")) != NULL)
        rpng2_info.display_exponent = atof(p);
    else
        rpng2_info.display_exponent = default_display_exponent;


    /* Now parse the command line for options and the PNG filename. */

    while (*++argv && !error) {
        if (!strncmp(*argv, "-display", 2)) {
            if (!*++argv)
                ++error;
            else
                displayname = *argv;
        } else if (!strncmp(*argv, "-gamma", 2)) {
            if (!*++argv)
                ++error;
            else {
                rpng2_info.display_exponent = atof(*argv);
                if (rpng2_info.display_exponent <= 0.0)
                    ++error;
            }
        } else if (!strncmp(*argv, "-bgcolor", 4)) {
            if (!*++argv)
                ++error;
            else {
                bgstr = *argv;
                if (strlen(bgstr) != 7 || bgstr[0] != '#')
                    ++error;
                else {
                    have_bg = TRUE;
                    bg_image = FALSE;
                }
            }
        } else if (!strncmp(*argv, "-bgpat", 4)) {
            if (!*++argv)
                ++error;
            else {
                pat = atoi(*argv);
                if (pat >= 0 && pat < num_bgpat) {
                    bg_image = TRUE;
                    have_bg = FALSE;
                } else
                    ++error;
            }
        } else if (!strncmp(*argv, "-usleep", 2)) {
            if (!*++argv)
                ++error;
            else {
                usleep_duration = (ulg)atol(*argv);
                demo_timing = TRUE;
            }
        } else if (!strncmp(*argv, "-pause", 2)) {
            pause_after_pass = TRUE;
        } else if (!strncmp(*argv, "-timing", 2)) {
            timing = TRUE;
#ifdef FEATURE_LOOP
        } else if (!strncmp(*argv, "-loop", 2)) {
            loop = TRUE;
            if (!argv[1] || !is_number(argv[1]))
                loop_interval = 2;
            else {
                ++argv;
                loop_interval = atol(*argv);
                if (loop_interval < 0)
                    loop_interval = 2;
                else if (loop_interval > 100000)   /* bit more than one day */
                    loop_interval = 100000;
            }
#endif
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__))
        } else if (!strncmp(*argv, "-nommxfilters", 7)) {
            rpng2_info.nommxfilters = TRUE;
        } else if (!strncmp(*argv, "-nommxcombine", 7)) {
            rpng2_info.nommxcombine = TRUE;
        } else if (!strncmp(*argv, "-nommxinterlace", 7)) {
            rpng2_info.nommxinterlace = TRUE;
        } else if (!strcmp(*argv, "-nommx")) {
            rpng2_info.nommxfilters = TRUE;
            rpng2_info.nommxcombine = TRUE;
            rpng2_info.nommxinterlace = TRUE;
#endif
        } else {
            if (**argv != '-') {
                filename = *argv;
                if (argv[1])   /* shouldn't be any more args after filename */
                    ++error;
            } else
                ++error;   /* not expecting any other options */
        }
    }

    if (!filename)
        ++error;


    /* print usage screen if any errors up to this point */

    if (error) {
        fprintf(stderr, "\n%s %s:  %s\n\n", PROGNAME, VERSION, appname);
        readpng2_version_info();
        fprintf(stderr, "\n"
          "Usage:  %s [-display xdpy] [-gamma exp] [-bgcolor bg | -bgpat pat]\n"
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__))
          "        %*s [[-nommxfilters] [-nommxcombine] [-nommxinterlace] | -nommx]\n"
#endif
#ifdef FEATURE_LOOP
          "        %*s [-usleep dur | -timing] [-pause] [-loop [sec]] file.png\n\n"
#else
          "        %*s [-usleep dur | -timing] [-pause] file.png\n\n"
#endif
          "    xdpy\tname of the target X display (e.g., ``hostname:0'')\n"
          "    exp \ttransfer-function exponent (``gamma'') of the display\n"
          "\t\t  system in floating-point format (e.g., ``%.1f''); equal\n"
          "\t\t  to the product of the lookup-table exponent (varies)\n"
          "\t\t  and the CRT exponent (usually 2.2); must be positive\n"
          "    bg  \tdesired background color in 7-character hex RGB format\n"
          "\t\t  (e.g., ``#ff7700'' for orange:  same as HTML colors);\n"
          "\t\t  used with transparent images; overrides -bgpat\n"
          "    pat \tdesired background pattern number (0-%d); used with\n"
          "\t\t  transparent images; overrides -bgcolor\n"
#ifdef FEATURE_LOOP
          "    -loop\tloops through background images after initial display\n"
          "\t\t  is complete (depends on -bgpat)\n"
          "    sec \tseconds to display each background image (default = 2)\n"
#endif
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__))
          "    -nommx*\tdisable optimized MMX routines for decoding row filters,\n"
          "\t\t  combining rows, and expanding interlacing, respectively\n"
#endif
          "    dur \tduration in microseconds to wait after displaying each\n"
          "\t\t  row (for demo purposes)\n"
          "    -timing\tenables delay for every block read, to simulate modem\n"
          "\t\t  download of image (~36 Kbps)\n"
          "    -pause\tpauses after displaying each pass until mouse clicked\n"
          "\nPress Q, Esc or mouse button 1 (within image window, after image\n"
          "is displayed) to quit.\n"
          "\n", PROGNAME,
#if (defined(__i386__) || defined(_M_IX86) || defined(__x86_64__))
          (int)strlen(PROGNAME), " ",
#endif
          (int)strlen(PROGNAME), " ", default_display_exponent, num_bgpat-1);
        exit(1);
    }


    if (!(infile = fopen(filename, "rb"))) {
        fprintf(stderr, PROGNAME ":  can't open PNG file [%s]\n", filename);
        ++error;
    } else {
        incount = fread(inbuf, 1, INBUFSIZE, infile);
        if (incount < 8 || !readpng2_check_sig(inbuf, 8)) {
            fprintf(stderr, PROGNAME
              ":  [%s] is not a PNG file: incorrect signature\n",
              filename);
            ++error;
        } else if ((rc = readpng2_init(&rpng2_info)) != 0) {
            switch (rc) {
                case 2:
                    fprintf(stderr, PROGNAME
                      ":  [%s] has bad IHDR (libpng longjmp)\n", filename);
                    break;
                case 4:
                    fprintf(stderr, PROGNAME ":  insufficient memory\n");
                    break;
                default:
                    fprintf(stderr, PROGNAME
                      ":  unknown readpng2_init() error\n");
                    break;
            }
            ++error;
        } else {
            Trace((stderr, "about to call XOpenDisplay()\n"))
            display = XOpenDisplay(displayname);
            if (!display) {
                readpng2_cleanup(&rpng2_info);
                fprintf(stderr, PROGNAME ":  can't open X display [%s]\n",
                  displayname? displayname : "default");
                ++error;
            }
        }
        if (error)
            fclose(infile);
    }


    if (error) {
        fprintf(stderr, PROGNAME ":  aborting.\n");
        exit(2);
    }


    /* set the title-bar string, but make sure buffer doesn't overflow */

    alen = strlen(appname);
    flen = strlen(filename);
    if (alen + flen + 3 > 1023)
        sprintf(titlebar, "%s:  ...%s", appname, filename+(alen+flen+6-1023));
    else
        sprintf(titlebar, "%s:  %s", appname, filename);


    /* set some final rpng2_info variables before entering main data loop */

    if (have_bg) {
        unsigned r, g, b;   /* this approach quiets compiler warnings */

        sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b);
        rpng2_info.bg_red   = (uch)r;
        rpng2_info.bg_green = (uch)g;
        rpng2_info.bg_blue  = (uch)b;
    } else
        rpng2_info.need_bgcolor = TRUE;

    rpng2_info.state = kPreInit;
    rpng2_info.mainprog_init = rpng2_x_init;
    rpng2_info.mainprog_display_row = rpng2_x_display_row;
    rpng2_info.mainprog_finish_display = rpng2_x_finish_display;


    /* OK, this is the fun part:  call readpng2_decode_data() at the start of
     * the loop to deal with our first buffer of data (read in above to verify
     * that the file is a PNG image), then loop through the file and continue
     * calling the same routine to handle each chunk of data.  It in turn
     * passes the data to libpng, which will invoke one or more of our call-
     * backs as decoded data become available.  We optionally call sleep() for
     * one second per iteration to simulate downloading the image via an analog
     * modem. */

    for (;;) {
        Trace((stderr, "about to call readpng2_decode_data()\n"))
        if (readpng2_decode_data(&rpng2_info, inbuf, incount))
            ++error;
        Trace((stderr, "done with readpng2_decode_data()\n"))

        if (error || incount != INBUFSIZE || rpng2_info.state == kDone) {
            if (rpng2_info.state == kDone) {
                Trace((stderr, "done decoding PNG image\n"))
            } else if (ferror(infile)) {
                fprintf(stderr, PROGNAME
                  ":  error while reading PNG image file\n");
                exit(3);
            } else if (feof(infile)) {
                fprintf(stderr, PROGNAME ":  end of file reached "
                  "(unexpectedly) while reading PNG image file\n");
                exit(3);
            } else /* if (error) */ {
                // will print error message below
            }
            break;
        }

        if (timing)
            sleep(1);

        incount = fread(inbuf, 1, INBUFSIZE, infile);
    }


    /* clean up PNG stuff and report any decoding errors */

    fclose(infile);
    Trace((stderr, "about to call readpng2_cleanup()\n"))
    readpng2_cleanup(&rpng2_info);

    if (error) {
        fprintf(stderr, PROGNAME ":  libpng error while decoding PNG image\n");
        exit(3);
    }


#ifdef FEATURE_LOOP

    if (loop && bg_image) {
        Trace((stderr, "entering -loop loop (FEATURE_LOOP)\n"))
        for (;;) {
            int i, use_sleep;
            struct timeval now, then;

            /* get current time and add loop_interval to get target time */
            if (gettimeofday(&then, NULL) == 0) {
                then.tv_sec += loop_interval;
                use_sleep = FALSE;
            } else
                use_sleep = TRUE;

            /* do quick check for a quit event but don't wait for it */
            /* GRR BUG:  should also check for Expose events and redraw... */
            if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask, &e))
                if (QUIT(e,k))
                    break;

            /* generate next background image */
            if (++pat >= num_bgpat)
                pat = 0;
            rpng2_x_reload_bg_image();

            /* wait for timeout, using whatever means are available */
            if (use_sleep || gettimeofday(&now, NULL) != 0) {
                for (i = loop_interval;  i > 0;  --i) {
                    sleep(1);
                    /* GRR BUG:  also need to check for Expose (and redraw!) */
                    if (XCheckMaskEvent(display, KeyPressMask | ButtonPressMask,
                        &e) && QUIT(e,k))
                        break;
                }
            } else {
                /* Y2038 BUG! */
                if (now.tv_sec < then.tv_sec ||
                    (now.tv_sec == then.tv_sec && now.tv_usec < then.tv_usec))
                {
                    int quit = FALSE;
                    long seconds_to_go = then.tv_sec - now.tv_sec;
                    long usleep_usec;

                    /* basically chew up most of remaining loop-interval with
                     *  calls to sleep(1) interleaved with checks for quit
                     *  events, but also recalc time-to-go periodically; when
                     *  done, clean up any remaining time with usleep() call
                     *  (could also use SIGALRM, but signals are a pain...) */
                    while (seconds_to_go-- > 1) {
                        int seconds_done = 0;

                        for (i = seconds_to_go;  i > 0 && !quit;  --i) {
                            sleep(1);
                            /* GRR BUG:  need to check for Expose and redraw */
                            if (XCheckMaskEvent(display, KeyPressMask |
                                ButtonPressMask, &e) && QUIT(e,k))
                                quit = TRUE;
                            if (++seconds_done > 1000)
                                break;   /* time to redo seconds_to_go meas. */
                        }
                        if (quit)
                            break;

                        /* OK, more than 1000 seconds since last check:
                         *  correct the time-to-go measurement for drift */
                        if (gettimeofday(&now, NULL) == 0) {
                            if (now.tv_sec >= then.tv_sec)
                                break;
                            seconds_to_go = then.tv_sec - now.tv_sec;
                        } else
                            ++seconds_to_go;  /* restore what we subtracted */
                    }
                    if (quit)
                        break;   /* breaks outer do-loop, skips redisplay */

                    /* since difference between "now" and "then" is already
                     *  eaten up to within a couple of seconds, don't need to
                     *  worry about overflow--but might have overshot (neg.) */
                    if (gettimeofday(&now, NULL) == 0) {
                        usleep_usec = 1000000L*(then.tv_sec - now.tv_sec) +
                          then.tv_usec - now.tv_usec;
                        if (usleep_usec > 0)
                            usleep((ulg)usleep_usec);
                    }
                }
            }

            /* composite image against new background and display (note that
             *  we do not take into account the time spent doing this...) */
            rpng2_x_redisplay_image (0, 0, rpng2_info.width, rpng2_info.height);
        }

    } else /* FALL THROUGH and do the normal thing */

#endif /* FEATURE_LOOP */

    /* wait for the user to tell us when to quit */

    if (rpng2_info.state >= kWindowInit) {
        Trace((stderr, "entering final wait-for-quit-event loop\n"))
        do {
            XNextEvent(display, &e);
            if (e.type == Expose) {
                XExposeEvent *ex = (XExposeEvent *)&e;
                rpng2_x_redisplay_image (ex->x, ex->y, ex->width, ex->height);
            }
        } while (!QUIT(e,k));
    } else {
        fprintf(stderr, PROGNAME ":  init callback never called:  probable "
          "libpng error while decoding PNG metadata\n");
        exit(4);
    }


    /* we're done:  clean up all image and X resources and go away */

    Trace((stderr, "about to call rpng2_x_cleanup()\n"))
    rpng2_x_cleanup();

    return 0;
}





/* this function is called by readpng2_info_callback() in readpng2.c, which
 * in turn is called by libpng after all of the pre-IDAT chunks have been
 * read and processed--i.e., we now have enough info to finish initializing */

static void rpng2_x_init(void)
{
    ulg i;
    ulg rowbytes = rpng2_info.rowbytes;

    Trace((stderr, "beginning rpng2_x_init()\n"))
    Trace((stderr, "  rowbytes = %d\n", rpng2_info.rowbytes))
    Trace((stderr, "  width  = %ld\n", rpng2_info.width))
    Trace((stderr, "  height = %ld\n", rpng2_info.height))

    rpng2_info.image_data = (uch *)malloc(rowbytes * rpng2_info.height);
    if (!rpng2_info.image_data) {
        readpng2_cleanup(&rpng2_info);
        return;
    }

    rpng2_info.row_pointers = (uch **)malloc(rpng2_info.height * sizeof(uch *));
    if (!rpng2_info.row_pointers) {
        free(rpng2_info.image_data);
        rpng2_info.image_data = NULL;
        readpng2_cleanup(&rpng2_info);
        return;
    }

    for (i = 0;  i < rpng2_info.height;  ++i)
        rpng2_info.row_pointers[i] = rpng2_info.image_data + i*rowbytes;


    /* do the basic X initialization stuff, make the window, and fill it with
     * the user-specified, file-specified or default background color or
     * pattern */

    if (rpng2_x_create_window()) {

        /* GRR TEMPORARY HACK:  this is fundamentally no different from cases
         * above; libpng should longjmp() back to us when png_ptr goes away.
         * If we/it segfault instead, seems like a libpng bug... */

        /* we're here via libpng callback, so if window fails, clean and bail */
        readpng2_cleanup(&rpng2_info);
        rpng2_x_cleanup();
        exit(2);
    }

    rpng2_info.state = kWindowInit;
}





static int rpng2_x_create_window(void)
{
    ulg bg_red   = rpng2_info.bg_red;
    ulg bg_green = rpng2_info.bg_green;
    ulg bg_blue  = rpng2_info.bg_blue;
    ulg bg_pixel = 0L;
    ulg attrmask;
    int need_colormap = FALSE;
    int screen, pad;
    uch *xdata;
    Window root;
    XEvent e;
    XGCValues gcvalues;
    XSetWindowAttributes attr;
    XTextProperty windowName, *pWindowName = &windowName;
    XTextProperty iconName, *pIconName = &iconName;
    XVisualInfo visual_info;
    XSizeHints *size_hints;
    XWMHints *wm_hints;
    XClassHint *class_hints;


    Trace((stderr, "beginning rpng2_x_create_window()\n"))

    screen = DefaultScreen(display);
    depth = DisplayPlanes(display, screen);
    root = RootWindow(display, screen);

#ifdef DEBUG
    XSynchronize(display, True);
#endif

    if (depth != 16 && depth != 24 && depth != 32) {
        int visuals_matched = 0;

        Trace((stderr, "default depth is %d:  checking other visuals\n",
          depth))

        /* 24-bit first */
        visual_info.screen = screen;
        visual_info.depth = 24;
        visual_list = XGetVisualInfo(display,
          VisualScreenMask | VisualDepthMask, &visual_info, &visuals_matched);
        if (visuals_matched == 0) {
/* GRR:  add 15-, 16- and 32-bit TrueColor visuals (also DirectColor?) */
            fprintf(stderr, "default screen depth %d not supported, and no"
              " 24-bit visuals found\n", depth);
            return 2;
        }
        Trace((stderr, "XGetVisualInfo() returned %d 24-bit visuals\n",
          visuals_matched))
        visual = visual_list[0].visual;
        depth = visual_list[0].depth;
/*
        colormap_size = visual_list[0].colormap_size;
        visual_class = visual->class;
        visualID = XVisualIDFromVisual(visual);
 */
        have_nondefault_visual = TRUE;
        need_colormap = TRUE;
    } else {
        XMatchVisualInfo(display, screen, depth, TrueColor, &visual_info);
        visual = visual_info.visual;
    }

    RMask = visual->red_mask;
    GMask = visual->green_mask;
    BMask = visual->blue_mask;

/* GRR:  add/check 8-bit support */
    if (depth == 8 || need_colormap) {
        colormap = XCreateColormap(display, root, visual, AllocNone);
        if (!colormap) {
            fprintf(stderr, "XCreateColormap() failed\n");
            return 2;
        }
        have_colormap = TRUE;
        if (depth == 8)
            bg_image = FALSE;   /* gradient just wastes palette entries */
    }
    if (depth == 15 || depth == 16) {
        RShift = 15 - rpng2_x_msb(RMask);    /* these are right-shifts */
        GShift = 15 - rpng2_x_msb(GMask);
        BShift = 15 - rpng2_x_msb(BMask);
    } else if (depth > 16) {
        RShift = rpng2_x_msb(RMask) - 7;     /* these are left-shifts */
        GShift = rpng2_x_msb(GMask) - 7;
        BShift = rpng2_x_msb(BMask) - 7;
    }
    if (depth >= 15 && (RShift < 0 || GShift < 0 || BShift < 0)) {
        fprintf(stderr, "rpng2 internal logic error:  negative X shift(s)!\n");
        return 2;
    }

/*---------------------------------------------------------------------------
    Finally, create the window.
  ---------------------------------------------------------------------------*/

    attr.backing_store = Always;
    attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask;
    attrmask = CWBackingStore | CWEventMask;
    if (have_nondefault_visual) {
        attr.colormap = colormap;
        attr.background_pixel = 0;
        attr.border_pixel = 1;
        attrmask |= CWColormap | CWBackPixel | CWBorderPixel;
    }

    window = XCreateWindow(display, root, 0, 0, rpng2_info.width,
      rpng2_info.height, 0, depth, InputOutput, visual, attrmask, &attr);

    if (window == None) {
        fprintf(stderr, "XCreateWindow() failed\n");
        return 2;
    } else
        have_window = TRUE;

    if (depth == 8)
        XSetWindowColormap(display, window, colormap);

    if (!XStringListToTextProperty(&window_name, 1, pWindowName))
        pWindowName = NULL;
    if (!XStringListToTextProperty(&icon_name, 1, pIconName))
        pIconName = NULL;

    /* OK if either hints allocation fails; XSetWMProperties() allows NULLs */

    if ((size_hints = XAllocSizeHints()) != NULL) {
        /* window will not be resizable */
        size_hints->flags = PMinSize | PMaxSize;
        size_hints->min_width = size_hints->max_width = (int)rpng2_info.width;
        size_hints->min_height = size_hints->max_height =
          (int)rpng2_info.height;
    }

    if ((wm_hints = XAllocWMHints()) != NULL) {
        wm_hints->initial_state = NormalState;
        wm_hints->input = True;
     /* wm_hints->icon_pixmap = icon_pixmap; */
        wm_hints->flags = StateHint | InputHint  /* | IconPixmapHint */ ;
    }

    if ((class_hints = XAllocClassHint()) != NULL) {
        class_hints->res_name = res_name;
        class_hints->res_class = res_class;
    }

    XSetWMProperties(display, window, pWindowName, pIconName, NULL, 0,
      size_hints, wm_hints, class_hints);

    /* various properties and hints no longer needed; free memory */
    if (pWindowName)
       XFree(pWindowName->value);
    if (pIconName)
       XFree(pIconName->value);
    if (size_hints)
        XFree(size_hints);
    if (wm_hints)
       XFree(wm_hints);
    if (class_hints)
       XFree(class_hints);

    XMapWindow(display, window);

    gc = XCreateGC(display, window, 0, &gcvalues);
    have_gc = TRUE;

/*---------------------------------------------------------------------------
    Allocate memory for the X- and display-specific version of the image.
  ---------------------------------------------------------------------------*/

    if (depth == 24 || depth == 32) {
        xdata = (uch *)malloc(4*rpng2_info.width*rpng2_info.height);
        pad = 32;
    } else if (depth == 16) {
        xdata = (uch *)malloc(2*rpng2_info.width*rpng2_info.height);
        pad = 16;
    } else /* depth == 8 */ {
        xdata = (uch *)malloc(rpng2_info.width*rpng2_info.height);
        pad = 8;
    }

    if (!xdata) {
        fprintf(stderr, PROGNAME ":  unable to allocate image memory\n");
        return 4;
    }

    ximage = XCreateImage(display, visual, depth, ZPixmap, 0,
      (char *)xdata, rpng2_info.width, rpng2_info.height, pad, 0);

    if (!ximage) {
        fprintf(stderr, PROGNAME ":  XCreateImage() failed\n");
        free(xdata);
        return 3;
    }

    /* to avoid testing the byte order every pixel (or doubling the size of
     * the drawing routine with a giant if-test), we arbitrarily set the byte
     * order to MSBFirst and let Xlib worry about inverting things on little-
     * endian machines (e.g., Linux/x86, old VAXen, etc.)--this is not the
     * most efficient approach (the giant if-test would be better), but in
     * the interest of clarity, we'll take the easy way out... */

    ximage->byte_order = MSBFirst;

/*---------------------------------------------------------------------------
    Fill window with the specified background color (default is black) or
    faked "background image" (but latter is disabled if 8-bit; gradients
    just waste palette entries).
  ---------------------------------------------------------------------------*/

    if (bg_image)
        rpng2_x_load_bg_image();    /* resets bg_image if fails */

    if (!bg_image) {
        if (depth == 24 || depth == 32) {
            bg_pixel = (bg_red   << RShift) |
                       (bg_green << GShift) |
                       (bg_blue  << BShift);
        } else if (depth == 16) {
            bg_pixel = (((bg_red   << 8) >> RShift) & RMask) |
                       (((bg_green << 8) >> GShift) & GMask) |
                       (((bg_blue  << 8) >> BShift) & BMask);
        } else /* depth == 8 */ {

            /* GRR:  add 8-bit support */

        }
        XSetForeground(display, gc, bg_pixel);
        XFillRectangle(display, window, gc, 0, 0, rpng2_info.width,
          rpng2_info.height);
    }

/*---------------------------------------------------------------------------
    Wait for first Expose event to do any drawing, then flush and return.
  ---------------------------------------------------------------------------*/

    do
        XNextEvent(display, &e);
    while (e.type != Expose || e.xexpose.count);

    XFlush(display);

    return 0;

} /* end function rpng2_x_create_window() */





static int rpng2_x_load_bg_image(void)
{
    uch *src;
    char *dest;
    uch r1, r2, g1, g2, b1, b2;
    uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv;
    int k, hmax, max;
    int xidx, yidx, yidx_max;
    int even_odd_vert, even_odd_horiz, even_odd;
    int invert_gradient2 = (bg[pat].type & 0x08);
    int invert_column;
    int ximage_rowbytes = ximage->bytes_per_line;
    ulg i, row;
    ulg pixel;

/*---------------------------------------------------------------------------
    Allocate buffer for fake background image to be used with transparent
    images; if this fails, revert to plain background color.
  ---------------------------------------------------------------------------*/

    bg_rowbytes = 3 * rpng2_info.width;
    bg_data = (uch *)malloc(bg_rowbytes * rpng2_info.height);
    if (!bg_data) {
        fprintf(stderr, PROGNAME
          ":  unable to allocate memory for background image\n");
        bg_image = 0;
        return 1;
    }

    bgscale = (pat == 0)? 8 : bgscale_default;
    yidx_max = bgscale - 1;

/*---------------------------------------------------------------------------
    Vertical gradients (ramps) in NxN squares, alternating direction and
    colors (N == bgscale).
  ---------------------------------------------------------------------------*/

    if ((bg[pat].type & 0x07) == 0) {
        uch r1_min  = rgb[bg[pat].rgb1_min].r;
        uch g1_min  = rgb[bg[pat].rgb1_min].g;
        uch b1_min  = rgb[bg[pat].rgb1_min].b;
        uch r2_min  = rgb[bg[pat].rgb2_min].r;
        uch g2_min  = rgb[bg[pat].rgb2_min].g;
        uch b2_min  = rgb[bg[pat].rgb2_min].b;
        int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min;
        int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min;
        int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min;
        int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min;
        int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min;
        int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            yidx = (int)(row % bgscale);
            even_odd_vert = (int)((row / bgscale) & 1);

            r1 = r1_min + (r1_diff * yidx) / yidx_max;
            g1 = g1_min + (g1_diff * yidx) / yidx_max;
            b1 = b1_min + (b1_diff * yidx) / yidx_max;
            r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max;
            g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max;
            b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max;

            r2 = r2_min + (r2_diff * yidx) / yidx_max;
            g2 = g2_min + (g2_diff * yidx) / yidx_max;
            b2 = b2_min + (b2_diff * yidx) / yidx_max;
            r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max;
            g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max;
            b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max;

            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                even_odd_horiz = (int)((i / bgscale) & 1);
                even_odd = even_odd_vert ^ even_odd_horiz;
                invert_column =
                  (even_odd_horiz && (bg[pat].type & 0x10));
                if (even_odd == 0) {        /* gradient #1 */
                    if (invert_column) {
                        *dest++ = r1_inv;
                        *dest++ = g1_inv;
                        *dest++ = b1_inv;
                    } else {
                        *dest++ = r1;
                        *dest++ = g1;
                        *dest++ = b1;
                    }
                } else {                    /* gradient #2 */
                    if ((invert_column && invert_gradient2) ||
                        (!invert_column && !invert_gradient2))
                    {
                        *dest++ = r2;       /* not inverted or */
                        *dest++ = g2;       /*  doubly inverted */
                        *dest++ = b2;
                    } else {
                        *dest++ = r2_inv;
                        *dest++ = g2_inv;   /* singly inverted */
                        *dest++ = b2_inv;
                    }
                }
            }
        }

/*---------------------------------------------------------------------------
    Soft gradient-diamonds with scale = bgscale.  Code contributed by Adam
    M. Costello.
  ---------------------------------------------------------------------------*/

    } else if ((bg[pat].type & 0x07) == 1) {

        hmax = (bgscale-1)/2;   /* half the max weight of a color */
        max = 2*hmax;           /* the max weight of a color */

        r1 = rgb[bg[pat].rgb1_max].r;
        g1 = rgb[bg[pat].rgb1_max].g;
        b1 = rgb[bg[pat].rgb1_max].b;
        r2 = rgb[bg[pat].rgb2_max].r;
        g2 = rgb[bg[pat].rgb2_max].g;
        b2 = rgb[bg[pat].rgb2_max].b;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            yidx = (int)(row % bgscale);
            if (yidx > hmax)
                yidx = bgscale-1 - yidx;
            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                xidx = (int)(i % bgscale);
                if (xidx > hmax)
                    xidx = bgscale-1 - xidx;
                k = xidx + yidx;
                *dest++ = (k*r1 + (max-k)*r2) / max;
                *dest++ = (k*g1 + (max-k)*g2) / max;
                *dest++ = (k*b1 + (max-k)*b2) / max;
            }
        }

/*---------------------------------------------------------------------------
    Radial "starburst" with azimuthal sinusoids; [eventually number of sinu-
    soids will equal bgscale?].  This one is slow but very cool.  Code con-
    tributed by Pieter S. van der Meulen (originally in Smalltalk).
  ---------------------------------------------------------------------------*/

    } else if ((bg[pat].type & 0x07) == 2) {
        uch ch;
        int ii, x, y, hw, hh, grayspot;
        double freq, rotate, saturate, gray, intensity;
        double angle=0.0, aoffset=0.0, maxDist, dist;
        double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t;

        fprintf(stderr, "%s:  computing radial background...",
          PROGNAME);
        fflush(stderr);

        hh = (int)(rpng2_info.height / 2);
        hw = (int)(rpng2_info.width / 2);

        /* variables for radial waves:
         *   aoffset:  number of degrees to rotate hue [CURRENTLY NOT USED]
         *   freq:  number of color beams originating from the center
         *   grayspot:  size of the graying center area (anti-alias)
         *   rotate:  rotation of the beams as a function of radius
         *   saturate:  saturation of beams' shape azimuthally
         */
        angle = CLIP(angle, 0.0, 360.0);
        grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw));
        freq = MAX((double)bg[pat].bg_freq, 0.0);
        saturate = (double)bg[pat].bg_bsat * 0.1;
        rotate = (double)bg[pat].bg_brot * 0.1;
        gray = 0.0;
        intensity = 0.0;
        maxDist = (double)((hw*hw) + (hh*hh));

        for (row = 0;  row < rpng2_info.height;  ++row) {
            y = (int)(row - hh);
            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                x = (int)(i - hw);
                angle = (x == 0)? PI_2 : atan((double)y / (double)x);
                gray = (double)MAX(ABS(y), ABS(x)) / grayspot;
                gray = MIN(1.0, gray);
                dist = (double)((x*x) + (y*y)) / maxDist;
                intensity = cos((angle+(rotate*dist*PI)) * freq) *
                  gray * saturate;
                intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5;
                hue = (angle + PI) * INV_PI_360 + aoffset;
                s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh));
                s = MIN(MAX(s,0.0), 1.0);
                v = MIN(MAX(intensity,0.0), 1.0);

                if (s == 0.0) {
                    ch = (uch)(v * 255.0);
                    *dest++ = ch;
                    *dest++ = ch;
                    *dest++ = ch;
                } else {
                    if ((hue < 0.0) || (hue >= 360.0))
                        hue -= (((int)(hue / 360.0)) * 360.0);
                    hue /= 60.0;
                    ii = (int)hue;
                    f = hue - (double)ii;
                    p = (1.0 - s) * v;
                    q = (1.0 - (s * f)) * v;
                    t = (1.0 - (s * (1.0 - f))) * v;
                    if      (ii == 0) { red = v; green = t; blue = p; }
                    else if (ii == 1) { red = q; green = v; blue = p; }
                    else if (ii == 2) { red = p; green = v; blue = t; }
                    else if (ii == 3) { red = p; green = q; blue = v; }
                    else if (ii == 4) { red = t; green = p; blue = v; }
                    else if (ii == 5) { red = v; green = p; blue = q; }
                    *dest++ = (uch)(red * 255.0);
                    *dest++ = (uch)(green * 255.0);
                    *dest++ = (uch)(blue * 255.0);
                }
            }
        }
        fprintf(stderr, "done.\n");
        fflush(stderr);
    }

/*---------------------------------------------------------------------------
    Blast background image to display buffer before beginning PNG decode.
  ---------------------------------------------------------------------------*/

    if (depth == 24 || depth == 32) {
        ulg red, green, blue;
        int bpp = ximage->bits_per_pixel;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            src = bg_data + row*bg_rowbytes;
            dest = ximage->data + row*ximage_rowbytes;
            if (bpp == 32) {	/* slightly optimized version */
                for (i = rpng2_info.width;  i > 0;  --i) {
                    red   = *src++;
                    green = *src++;
                    blue  = *src++;
                    pixel = (red   << RShift) |
                            (green << GShift) |
                            (blue  << BShift);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    *dest++ = (char)((pixel >> 24) & 0xff);
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            } else {
                for (i = rpng2_info.width;  i > 0;  --i) {
                    red   = *src++;
                    green = *src++;
                    blue  = *src++;
                    pixel = (red   << RShift) |
                            (green << GShift) |
                            (blue  << BShift);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    /* GRR BUG?  this assumes bpp == 24 & bits are packed low */
                    /*           (probably need to use RShift, RMask, etc.) */
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            }
        }

    } else if (depth == 16) {
        ush red, green, blue;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            src = bg_data + row*bg_rowbytes;
            dest = ximage->data + row*ximage_rowbytes;
            for (i = rpng2_info.width;  i > 0;  --i) {
                red   = ((ush)(*src) << 8);  ++src;
                green = ((ush)(*src) << 8);  ++src;
                blue  = ((ush)(*src) << 8);  ++src;
                pixel = ((red   >> RShift) & RMask) |
                        ((green >> GShift) & GMask) |
                        ((blue  >> BShift) & BMask);
                /* recall that we set ximage->byte_order = MSBFirst above */
                *dest++ = (char)((pixel >>  8) & 0xff);
                *dest++ = (char)( pixel        & 0xff);
            }
        }

    } else /* depth == 8 */ {

        /* GRR:  add 8-bit support */

    }

    XPutImage(display, window, gc, ximage, 0, 0, 0, 0, rpng2_info.width,
      rpng2_info.height);

    return 0;

} /* end function rpng2_x_load_bg_image() */





static void rpng2_x_display_row(ulg row)
{
    uch bg_red   = rpng2_info.bg_red;
    uch bg_green = rpng2_info.bg_green;
    uch bg_blue  = rpng2_info.bg_blue;
    uch *src, *src2=NULL;
    char *dest;
    uch r, g, b, a;
    int ximage_rowbytes = ximage->bytes_per_line;
    ulg i, pixel;
    static int rows=0, prevpass=(-1);
    static ulg firstrow;

/*---------------------------------------------------------------------------
    rows and firstrow simply track how many rows (and which ones) have not
    yet been displayed; alternatively, we could call XPutImage() for every
    row and not bother with the records-keeping.
  ---------------------------------------------------------------------------*/

    Trace((stderr, "beginning rpng2_x_display_row()\n"))

    if (rpng2_info.pass != prevpass) {
        if (pause_after_pass && rpng2_info.pass > 0) {
            XEvent e;
            KeySym k;

            fprintf(stderr,
              "%s:  end of pass %d of 7; click in image window to continue\n",
              PROGNAME, prevpass + 1);
            do
                XNextEvent(display, &e);
            while (!QUIT(e,k));
        }
        fprintf(stderr, "%s:  pass %d of 7\r", PROGNAME, rpng2_info.pass + 1);
        fflush(stderr);
        prevpass = rpng2_info.pass;
    }

    if (rows == 0)
        firstrow = row;   /* first row that is not yet displayed */

    ++rows;   /* count of rows received but not yet displayed */

/*---------------------------------------------------------------------------
    Aside from the use of the rpng2_info struct, the lack of an outer loop
    (over rows) and moving the XPutImage() call outside the "if (depth)"
    tests, this routine is identical to rpng_x_display_image() in the non-
    progressive version of the program.
  ---------------------------------------------------------------------------*/

    if (depth == 24 || depth == 32) {
        ulg red, green, blue;
        int bpp = ximage->bits_per_pixel;

        src = rpng2_info.image_data + row*rpng2_info.rowbytes;
        if (bg_image)
            src2 = bg_data + row*bg_rowbytes;
        dest = ximage->data + row*ximage_rowbytes;
        if (rpng2_info.channels == 3) {
            for (i = rpng2_info.width;  i > 0;  --i) {
                red   = *src++;
                green = *src++;
                blue  = *src++;
                pixel = (red   << RShift) |
                        (green << GShift) |
                        (blue  << BShift);
                /* recall that we set ximage->byte_order = MSBFirst above */
                if (bpp == 32) {
                    *dest++ = (char)((pixel >> 24) & 0xff);
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                } else {
                    /* GRR BUG?  this assumes bpp == 24 & bits are packed low */
                    /*           (probably need to use RShift, RMask, etc.) */
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            }
        } else /* if (rpng2_info.channels == 4) */ {
            for (i = rpng2_info.width;  i > 0;  --i) {
                r = *src++;
                g = *src++;
                b = *src++;
                a = *src++;
                if (bg_image) {
                    bg_red   = *src2++;
                    bg_green = *src2++;
                    bg_blue  = *src2++;
                }
                if (a == 255) {
                    red   = r;
                    green = g;
                    blue  = b;
                } else if (a == 0) {
                    red   = bg_red;
                    green = bg_green;
                    blue  = bg_blue;
                } else {
                    /* this macro (from png.h) composites the foreground
                     * and background values and puts the result into the
                     * first argument */
                    alpha_composite(red,   r, a, bg_red);
                    alpha_composite(green, g, a, bg_green);
                    alpha_composite(blue,  b, a, bg_blue);
                }
                pixel = (red   << RShift) |
                        (green << GShift) |
                        (blue  << BShift);
                /* recall that we set ximage->byte_order = MSBFirst above */
                if (bpp == 32) {
                    *dest++ = (char)((pixel >> 24) & 0xff);
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                } else {
                    /* GRR BUG?  this assumes bpp == 24 & bits are packed low */
                    /*           (probably need to use RShift, RMask, etc.) */
                    *dest++ = (char)((pixel >> 16) & 0xff);
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            }
        }

    } else if (depth == 16) {
        ush red, green, blue;

        src = rpng2_info.row_pointers[row];
        if (bg_image)
            src2 = bg_data + row*bg_rowbytes;
        dest = ximage->data + row*ximage_rowbytes;
        if (rpng2_info.channels == 3) {
            for (i = rpng2_info.width;  i > 0;  --i) {
                red   = ((ush)(*src) << 8);
                ++src;
                green = ((ush)(*src) << 8);
                ++src;
                blue  = ((ush)(*src) << 8);
                ++src;
                pixel = ((red   >> RShift) & RMask) |
                        ((green >> GShift) & GMask) |
                        ((blue  >> BShift) & BMask);
                /* recall that we set ximage->byte_order = MSBFirst above */
                *dest++ = (char)((pixel >>  8) & 0xff);
                *dest++ = (char)( pixel        & 0xff);
            }
        } else /* if (rpng2_info.channels == 4) */ {
            for (i = rpng2_info.width;  i > 0;  --i) {
                r = *src++;
                g = *src++;
                b = *src++;
                a = *src++;
                if (bg_image) {
                    bg_red   = *src2++;
                    bg_green = *src2++;
                    bg_blue  = *src2++;
                }
                if (a == 255) {
                    red   = ((ush)r << 8);
                    green = ((ush)g << 8);
                    blue  = ((ush)b << 8);
                } else if (a == 0) {
                    red   = ((ush)bg_red   << 8);
                    green = ((ush)bg_green << 8);
                    blue  = ((ush)bg_blue  << 8);
                } else {
                    /* this macro (from png.h) composites the foreground
                     * and background values and puts the result back into
                     * the first argument (== fg byte here:  safe) */
                    alpha_composite(r, r, a, bg_red);
                    alpha_composite(g, g, a, bg_green);
                    alpha_composite(b, b, a, bg_blue);
                    red   = ((ush)r << 8);
                    green = ((ush)g << 8);
                    blue  = ((ush)b << 8);
                }
                pixel = ((red   >> RShift) & RMask) |
                        ((green >> GShift) & GMask) |
                        ((blue  >> BShift) & BMask);
                /* recall that we set ximage->byte_order = MSBFirst above */
                *dest++ = (char)((pixel >>  8) & 0xff);
                *dest++ = (char)( pixel        & 0xff);
            }
        }

    } else /* depth == 8 */ {

        /* GRR:  add 8-bit support */

    }


/*---------------------------------------------------------------------------
    Display after every 16 rows or when on one of last two rows.  (Region
    may include previously displayed lines due to interlacing--i.e., not
    contiguous.  Also, second-to-last row is final one in interlaced images
    with odd number of rows.)  For demos, flush (and delay) after every 16th
    row so "sparse" passes don't go twice as fast.
  ---------------------------------------------------------------------------*/

    if (demo_timing && (row - firstrow >= 16 || row >= rpng2_info.height-2)) {
        XPutImage(display, window, gc, ximage, 0, (int)firstrow, 0,
          (int)firstrow, rpng2_info.width, row - firstrow + 1);
        XFlush(display);
        rows = 0;
        usleep(usleep_duration);
    } else
    if (!demo_timing && ((rows & 0xf) == 0 || row >= rpng2_info.height-2)) {
        XPutImage(display, window, gc, ximage, 0, (int)firstrow, 0,
          (int)firstrow, rpng2_info.width, row - firstrow + 1);
        XFlush(display);
        rows = 0;
    }

}





static void rpng2_x_finish_display(void)
{
    Trace((stderr, "beginning rpng2_x_finish_display()\n"))

    /* last row has already been displayed by rpng2_x_display_row(), so we
     * have nothing to do here except set a flag and let the user know that
     * the image is done */

    rpng2_info.state = kDone;
    printf(
      "Done.  Press Q, Esc or mouse button 1 (within image window) to quit.\n");
    fflush(stdout);
}





static void rpng2_x_redisplay_image(ulg startcol, ulg startrow,
                                    ulg width, ulg height)
{
    uch bg_red   = rpng2_info.bg_red;
    uch bg_green = rpng2_info.bg_green;
    uch bg_blue  = rpng2_info.bg_blue;
    uch *src, *src2=NULL;
    char *dest;
    uch r, g, b, a;
    ulg i, row, lastrow = 0;
    ulg pixel;
    int ximage_rowbytes = ximage->bytes_per_line;


    Trace((stderr, "beginning display loop (image_channels == %d)\n",
      rpng2_info.channels))
    Trace((stderr, "   (width = %ld, rowbytes = %d, ximage_rowbytes = %d)\n",
      rpng2_info.width, rpng2_info.rowbytes, ximage_rowbytes))
    Trace((stderr, "   (bpp = %d)\n", ximage->bits_per_pixel))
    Trace((stderr, "   (byte_order = %s)\n", ximage->byte_order == MSBFirst?
      "MSBFirst" : (ximage->byte_order == LSBFirst? "LSBFirst" : "unknown")))

/*---------------------------------------------------------------------------
    Aside from the use of the rpng2_info struct and of src2 (for background
    image), this routine is identical to rpng_x_display_image() in the non-
    progressive version of the program--for the simple reason that redisplay
    of the image against a new background happens after the image is fully
    decoded and therefore is, by definition, non-progressive.
  ---------------------------------------------------------------------------*/

    if (depth == 24 || depth == 32) {
        ulg red, green, blue;
        int bpp = ximage->bits_per_pixel;

        for (lastrow = row = startrow;  row < startrow+height;  ++row) {
            src = rpng2_info.image_data + row*rpng2_info.rowbytes;
            if (bg_image)
                src2 = bg_data + row*bg_rowbytes;
            dest = ximage->data + row*ximage_rowbytes;
            if (rpng2_info.channels == 3) {
                for (i = rpng2_info.width;  i > 0;  --i) {
                    red   = *src++;
                    green = *src++;
                    blue  = *src++;
#ifdef NO_24BIT_MASKS
                    pixel = (red   << RShift) |
                            (green << GShift) |
                            (blue  << BShift);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    if (bpp == 32) {
                        *dest++ = (char)((pixel >> 24) & 0xff);
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    } else {
                        /* this assumes bpp == 24 & bits are packed low */
                        /* (probably need to use RShift, RMask, etc.) */
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    }
#else
                    red   = (RShift < 0)? red   << (-RShift) : red   >> RShift;
                    green = (GShift < 0)? green << (-GShift) : green >> GShift;
                    blue  = (BShift < 0)? blue  << (-BShift) : blue  >> BShift;
                    pixel = (red & RMask) | (green & GMask) | (blue & BMask);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    if (bpp == 32) {
                        *dest++ = (char)((pixel >> 24) & 0xff);
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    } else {
                        /* GRR BUG */
                        /* this assumes bpp == 24 & bits are packed low */
                        /* (probably need to use RShift/RMask/etc. here, too) */
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    }
#endif
                }

            } else /* if (rpng2_info.channels == 4) */ {
                for (i = rpng2_info.width;  i > 0;  --i) {
                    r = *src++;
                    g = *src++;
                    b = *src++;
                    a = *src++;
                    if (bg_image) {
                        bg_red   = *src2++;
                        bg_green = *src2++;
                        bg_blue  = *src2++;
                    }
                    if (a == 255) {
                        red   = r;
                        green = g;
                        blue  = b;
                    } else if (a == 0) {
                        red   = bg_red;
                        green = bg_green;
                        blue  = bg_blue;
                    } else {
                        /* this macro (from png.h) composites the foreground
                         * and background values and puts the result into the
                         * first argument */
                        alpha_composite(red,   r, a, bg_red);
                        alpha_composite(green, g, a, bg_green);
                        alpha_composite(blue,  b, a, bg_blue);
                    }
#ifdef NO_24BIT_MASKS
                    pixel = (red   << RShift) |
                            (green << GShift) |
                            (blue  << BShift);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    if (bpp == 32) {
                        *dest++ = (char)((pixel >> 24) & 0xff);
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    } else {
                        /* this assumes bpp == 24 & bits are packed low */
                        /* (probably need to use RShift, RMask, etc.) */
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    }
#else
                    red   = (RShift < 0)? red   << (-RShift) : red   >> RShift;
                    green = (GShift < 0)? green << (-GShift) : green >> GShift;
                    blue  = (BShift < 0)? blue  << (-BShift) : blue  >> BShift;
                    pixel = (red & RMask) | (green & GMask) | (blue & BMask);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    if (bpp == 32) {
                        *dest++ = (char)((pixel >> 24) & 0xff);
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    } else {
                        /* GRR BUG */
                        /* this assumes bpp == 24 & bits are packed low */
                        /* (probably need to use RShift/RMask/etc. here, too) */
                        *dest++ = (char)((pixel >> 16) & 0xff);
                        *dest++ = (char)((pixel >>  8) & 0xff);
                        *dest++ = (char)( pixel        & 0xff);
                    }
#endif
                }
            }
            /* display after every 16 lines */
            if (((row+1) & 0xf) == 0) {
                XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
                  (int)lastrow, rpng2_info.width, 16);
                XFlush(display);
                lastrow = row + 1;
            }
        }

    } else if (depth == 16) {
        ush red, green, blue;

        for (lastrow = row = startrow;  row < startrow+height;  ++row) {
            src = rpng2_info.row_pointers[row];
            if (bg_image)
                src2 = bg_data + row*bg_rowbytes;
            dest = ximage->data + row*ximage_rowbytes;
            if (rpng2_info.channels == 3) {
                for (i = rpng2_info.width;  i > 0;  --i) {
                    red   = ((ush)(*src) << 8);
                    ++src;
                    green = ((ush)(*src) << 8);
                    ++src;
                    blue  = ((ush)(*src) << 8);
                    ++src;
                    pixel = ((red   >> RShift) & RMask) |
                            ((green >> GShift) & GMask) |
                            ((blue  >> BShift) & BMask);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            } else /* if (rpng2_info.channels == 4) */ {
                for (i = rpng2_info.width;  i > 0;  --i) {
                    r = *src++;
                    g = *src++;
                    b = *src++;
                    a = *src++;
                    if (bg_image) {
                        bg_red   = *src2++;
                        bg_green = *src2++;
                        bg_blue  = *src2++;
                    }
                    if (a == 255) {
                        red   = ((ush)r << 8);
                        green = ((ush)g << 8);
                        blue  = ((ush)b << 8);
                    } else if (a == 0) {
                        red   = ((ush)bg_red   << 8);
                        green = ((ush)bg_green << 8);
                        blue  = ((ush)bg_blue  << 8);
                    } else {
                        /* this macro (from png.h) composites the foreground
                         * and background values and puts the result back into
                         * the first argument (== fg byte here:  safe) */
                        alpha_composite(r, r, a, bg_red);
                        alpha_composite(g, g, a, bg_green);
                        alpha_composite(b, b, a, bg_blue);
                        red   = ((ush)r << 8);
                        green = ((ush)g << 8);
                        blue  = ((ush)b << 8);
                    }
                    pixel = ((red   >> RShift) & RMask) |
                            ((green >> GShift) & GMask) |
                            ((blue  >> BShift) & BMask);
                    /* recall that we set ximage->byte_order = MSBFirst above */
                    *dest++ = (char)((pixel >>  8) & 0xff);
                    *dest++ = (char)( pixel        & 0xff);
                }
            }
            /* display after every 16 lines */
            if (((row+1) & 0xf) == 0) {
                XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
                  (int)lastrow, rpng2_info.width, 16);
                XFlush(display);
                lastrow = row + 1;
            }
        }

    } else /* depth == 8 */ {

        /* GRR:  add 8-bit support */

    }

    Trace((stderr, "calling final XPutImage()\n"))
    if (lastrow < startrow+height) {
        XPutImage(display, window, gc, ximage, 0, (int)lastrow, 0,
          (int)lastrow, rpng2_info.width, rpng2_info.height-lastrow);
        XFlush(display);
    }

} /* end function rpng2_x_redisplay_image() */





#ifdef FEATURE_LOOP

static void rpng2_x_reload_bg_image(void)
{
    char *dest;
    uch r1, r2, g1, g2, b1, b2;
    uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv;
    int k, hmax, max;
    int xidx, yidx, yidx_max;
    int even_odd_vert, even_odd_horiz, even_odd;
    int invert_gradient2 = (bg[pat].type & 0x08);
    int invert_column;
    ulg i, row;


    bgscale = (pat == 0)? 8 : bgscale_default;
    yidx_max = bgscale - 1;

/*---------------------------------------------------------------------------
    Vertical gradients (ramps) in NxN squares, alternating direction and
    colors (N == bgscale).
  ---------------------------------------------------------------------------*/

    if ((bg[pat].type & 0x07) == 0) {
        uch r1_min  = rgb[bg[pat].rgb1_min].r;
        uch g1_min  = rgb[bg[pat].rgb1_min].g;
        uch b1_min  = rgb[bg[pat].rgb1_min].b;
        uch r2_min  = rgb[bg[pat].rgb2_min].r;
        uch g2_min  = rgb[bg[pat].rgb2_min].g;
        uch b2_min  = rgb[bg[pat].rgb2_min].b;
        int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min;
        int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min;
        int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min;
        int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min;
        int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min;
        int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            yidx = (int)(row % bgscale);
            even_odd_vert = (int)((row / bgscale) & 1);

            r1 = r1_min + (r1_diff * yidx) / yidx_max;
            g1 = g1_min + (g1_diff * yidx) / yidx_max;
            b1 = b1_min + (b1_diff * yidx) / yidx_max;
            r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max;
            g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max;
            b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max;

            r2 = r2_min + (r2_diff * yidx) / yidx_max;
            g2 = g2_min + (g2_diff * yidx) / yidx_max;
            b2 = b2_min + (b2_diff * yidx) / yidx_max;
            r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max;
            g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max;
            b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max;

            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                even_odd_horiz = (int)((i / bgscale) & 1);
                even_odd = even_odd_vert ^ even_odd_horiz;
                invert_column =
                  (even_odd_horiz && (bg[pat].type & 0x10));
                if (even_odd == 0) {        /* gradient #1 */
                    if (invert_column) {
                        *dest++ = r1_inv;
                        *dest++ = g1_inv;
                        *dest++ = b1_inv;
                    } else {
                        *dest++ = r1;
                        *dest++ = g1;
                        *dest++ = b1;
                    }
                } else {                    /* gradient #2 */
                    if ((invert_column && invert_gradient2) ||
                        (!invert_column && !invert_gradient2))
                    {
                        *dest++ = r2;       /* not inverted or */
                        *dest++ = g2;       /*  doubly inverted */
                        *dest++ = b2;
                    } else {
                        *dest++ = r2_inv;
                        *dest++ = g2_inv;   /* singly inverted */
                        *dest++ = b2_inv;
                    }
                }
            }
        }

/*---------------------------------------------------------------------------
    Soft gradient-diamonds with scale = bgscale.  Code contributed by Adam
    M. Costello.
  ---------------------------------------------------------------------------*/

    } else if ((bg[pat].type & 0x07) == 1) {

        hmax = (bgscale-1)/2;   /* half the max weight of a color */
        max = 2*hmax;           /* the max weight of a color */

        r1 = rgb[bg[pat].rgb1_max].r;
        g1 = rgb[bg[pat].rgb1_max].g;
        b1 = rgb[bg[pat].rgb1_max].b;
        r2 = rgb[bg[pat].rgb2_max].r;
        g2 = rgb[bg[pat].rgb2_max].g;
        b2 = rgb[bg[pat].rgb2_max].b;

        for (row = 0;  row < rpng2_info.height;  ++row) {
            yidx = (int)(row % bgscale);
            if (yidx > hmax)
                yidx = bgscale-1 - yidx;
            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                xidx = (int)(i % bgscale);
                if (xidx > hmax)
                    xidx = bgscale-1 - xidx;
                k = xidx + yidx;
                *dest++ = (k*r1 + (max-k)*r2) / max;
                *dest++ = (k*g1 + (max-k)*g2) / max;
                *dest++ = (k*b1 + (max-k)*b2) / max;
            }
        }

/*---------------------------------------------------------------------------
    Radial "starburst" with azimuthal sinusoids; [eventually number of sinu-
    soids will equal bgscale?].  This one is slow but very cool.  Code con-
    tributed by Pieter S. van der Meulen (originally in Smalltalk).
  ---------------------------------------------------------------------------*/

    } else if ((bg[pat].type & 0x07) == 2) {
        uch ch;
        int ii, x, y, hw, hh, grayspot;
        double freq, rotate, saturate, gray, intensity;
        double angle=0.0, aoffset=0.0, maxDist, dist;
        double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t;

        hh = (int)(rpng2_info.height / 2);
        hw = (int)(rpng2_info.width / 2);

        /* variables for radial waves:
         *   aoffset:  number of degrees to rotate hue [CURRENTLY NOT USED]
         *   freq:  number of color beams originating from the center
         *   grayspot:  size of the graying center area (anti-alias)
         *   rotate:  rotation of the beams as a function of radius
         *   saturate:  saturation of beams' shape azimuthally
         */
        angle = CLIP(angle, 0.0, 360.0);
        grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw));
        freq = MAX((double)bg[pat].bg_freq, 0.0);
        saturate = (double)bg[pat].bg_bsat * 0.1;
        rotate = (double)bg[pat].bg_brot * 0.1;
        gray = 0.0;
        intensity = 0.0;
        maxDist = (double)((hw*hw) + (hh*hh));

        for (row = 0;  row < rpng2_info.height;  ++row) {
            y = (int)(row - hh);
            dest = (char *)bg_data + row*bg_rowbytes;
            for (i = 0;  i < rpng2_info.width;  ++i) {
                x = (int)(i - hw);
                angle = (x == 0)? PI_2 : atan((double)y / (double)x);
                gray = (double)MAX(ABS(y), ABS(x)) / grayspot;
                gray = MIN(1.0, gray);
                dist = (double)((x*x) + (y*y)) / maxDist;
                intensity = cos((angle+(rotate*dist*PI)) * freq) *
                  gray * saturate;
                intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5;
                hue = (angle + PI) * INV_PI_360 + aoffset;
                s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh));
                s = MIN(MAX(s,0.0), 1.0);
                v = MIN(MAX(intensity,0.0), 1.0);

                if (s == 0.0) {
                    ch = (uch)(v * 255.0);
                    *dest++ = ch;
                    *dest++ = ch;
                    *dest++ = ch;
                } else {
                    if ((hue < 0.0) || (hue >= 360.0))
                        hue -= (((int)(hue / 360.0)) * 360.0);
                    hue /= 60.0;
                    ii = (int)hue;
                    f = hue - (double)ii;
                    p = (1.0 - s) * v;
                    q = (1.0 - (s * f)) * v;
                    t = (1.0 - (s * (1.0 - f))) * v;
                    if      (ii == 0) { red = v; green = t; blue = p; }
                    else if (ii == 1) { red = q; green = v; blue = p; }
                    else if (ii == 2) { red = p; green = v; blue = t; }
                    else if (ii == 3) { red = p; green = q; blue = v; }
                    else if (ii == 4) { red = t; green = p; blue = v; }
                    else if (ii == 5) { red = v; green = p; blue = q; }
                    *dest++ = (uch)(red * 255.0);
                    *dest++ = (uch)(green * 255.0);
                    *dest++ = (uch)(blue * 255.0);
                }
            }
        }
    }

} /* end function rpng2_x_reload_bg_image() */





static int is_number(char *p)
{
    while (*p) {
        if (!isdigit(*p))
            return FALSE;
        ++p;
    }
    return TRUE;
}

#endif /* FEATURE_LOOP */





static void rpng2_x_cleanup(void)
{
    if (bg_image && bg_data) {
        free(bg_data);
        bg_data = NULL;
    }

    if (rpng2_info.image_data) {
        free(rpng2_info.image_data);
        rpng2_info.image_data = NULL;
    }

    if (rpng2_info.row_pointers) {
        free(rpng2_info.row_pointers);
        rpng2_info.row_pointers = NULL;
    }

    if (ximage) {
        if (ximage->data) {
            free(ximage->data);           /* we allocated it, so we free it */
            ximage->data = (char *)NULL;  /*  instead of XDestroyImage() */
        }
        XDestroyImage(ximage);
        ximage = NULL;
    }

    if (have_gc)
        XFreeGC(display, gc);

    if (have_window)
        XDestroyWindow(display, window);

    if (have_colormap)
        XFreeColormap(display, colormap);

    if (have_nondefault_visual)
        XFree(visual_list);
}





static int rpng2_x_msb(ulg u32val)
{
    int i;

    for (i = 31;  i >= 0;  --i) {
        if (u32val & 0x80000000L)
            break;
        u32val <<= 1;
    }
    return i;
}