File: zfuncs.cc

package info (click to toggle)
fotoxx 24.70-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 21,888 kB
  • sloc: cpp: 78,255; makefile: 116; xml: 52
file content (14041 lines) | stat: -rw-r--r-- 499,088 bytes parent folder | download
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
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
/********************************************************************************

   zfuncs.cc   collection of Linux and GDK/GTK utility functions

   Copyright 2007-2024 Michael Cornelison
   source code URL: https://kornelix.net
   contact: mkornelix@gmail.com

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version. See https://www.gnu.org/licenses

   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.

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

#include "zfuncs.h"

#define RELEASE 24.70       //  follows Fotocx release versions

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

   System Utility Functions
   ------------------------
   zmalloc  zfree          wrappers to add add checks and statistics
   zstrdup                 duplicate string in allocated memory with added space
   zmalloc_test            check if planned allocation is available
   realmemory              get real free memory (incl. file cache) in MB units
   availmemory             get available memory (incl. swap file) in MB units
   Plog                    add message to stdout log file, fflush()
   xmessage                output a popup message not requiring GTK
   zexit                   exit process and kill subprocesses, opt. (popup) message
   zbacktrace              callable backtrace dump
   zappcrash               abort with traceback dump to desktop file
   catch_signals           trap segfault, crash with zappcrash()
   TRACE                   trace() and tracedump() implement the TRACE macro
   beroot                  restart image as root, if password is OK
   runroot                 run a command or program as root user
   combine_argvs           catenate argv[ii] elements from Nth to last
   get_seconds             get time in real seconds with millisecond resolution
   logtime                 log elapsed time since last call to logtime()
   start_timer             start a named timer
   get_timer               get elapsed time with millisecond resolution
   start_CPUtimer          start CPU process time timer
   get_CPUtimer            get elapsed CPU process time
   CPUtime                 get CPU process time for current process, seconds
   memused                 get real memory used by current process, MB
   proc_resources          get CPU and BIO usage for current and child processes
   compact_time            convert time_t type to yyyymmddhhmmss format
   secs_datetime           seconds since 1970 (double) to yymmddhhmmss (int[6])
   datetime_secs           yymmddhhmmss (int[6]) to seconds since 1970 (double)
   pretty_datetime         convert time_t type to yyyy-mm-dd hh:mm:ss format
   parseprocfile           read and parse /proc records formatted "parmname value"
   parseprocrec            read and parse /proc records with fixed series of values
   get_smp_counts          get processor performance and efficiency core counts
   coretemp                get current processor core temperature
   disktemp                get temperature for given disk drive
   zsleep                  sleep for any amount of time (e.g. 0.1 seconds)
   zloop                   loop for any amount of time
   spinlock                simple method to prevent parallel execution of code block
   global_lock             lock/unlock a global resource (all processes/threads)
   resource_lock           lock/unlock a resource within a process and threads
   zget_locked, etc.       safely get/put/increment parameters from multiple threads
   start_detached_thread   start a detached thread
   start_Jthread           start a joinable thread
   wait_Jthread            wait for thread and join
   synch_threads           make threads pause and resume together
   main_thread             return 1 if main() thread, else 0
   set_cpu_affinity        set CPU (SMP) affinity for calling process or thread
   zshell                  run shell command with options log, ack
   signalProc              pause, resume, or kill a child process
   fgets_trim              fgets() with trim of trailing \r \n and optionally blanks
   samefolder              test if two files/folders have the same folder path
   parsefile               parse filespec into folder, file, extension
   renamez                 like rename() but works across file systems
   check_create_dir        check if folder exists, ask to create if not
   cp_copy                 same, using shell "cp -f -p"
   diskspace               get available space on disk of given file, MB
   fix_file_extension      use 'file' command to find and append correct extension
   zreaddir                return all files in a folder, sorted
   zreadfile               read file, return array of records
   zwritefile              write array of records to file
   zreadfile_free          free zreadfile() memory
   cpu_profile             measure CPU time spent per function or code block
   pagefaultrate           monitor and report own process hard page fault rate

   String Functions
   ----------------
   substringR              get delimited substrings from input string
   substring               same, not thread-safe, no zfree() needed
   strHash                 hash string to random number in a range
   strncpy0                strncpy() with insured null delimiter
   strnPad                 add blank padding to specified length
   strTrim                 remove trailing blanks
   strTrim2                remove leading and trailing blanks
   strCompress             remove embedded blanks
   strncatv                catenate multiple strings with length limit
   strmatchV               compare 1 string to N strings
   strToUpper              convert string to upper case
   strToLower              convert string to lower case
   repl_1str               replace a substring within a string
   repl_Nstrs              replace multiple substrings within string
   breakup_text            insert newline chars to limit text line lengths
   strncpyx                convert string to hex format
   StripZeros              remove trailing zeros (1.23000E+8 >> 1.23E+8)
   blank_null              test string for null pointer, zero length, and all blanks
   clean_escapes           replace 2-character escapes ("\n") with the escaped characters
   UTF-8 functions         deal with UTF-8 multibyte character strings
   zsed                    substitute multiple strings in a file
   zstrstr                 zstrstr() and zcasestrstr() work like strstr() and strcasestr()
   zstrcasestr               but the string "" does NOT match with any string
   zstrcpy                 strcpy with overlap allowed
   zstrncpy                strncpy with overlap allowed
   zstrcmp                 like strcmp, but \n as well as null ends the compare
   zstrcmp2                works like strcmp(), but using ch *args instead of cch *
   zstrcasecmp             works like strcasecmp(), but using ch *args instead of cch *
   zescape_quotes          escape quote marks (",') for strings used in shell commands

   Number Conversion and Formatting
   --------------------------------
   convSI            string to integer with optional limits check
   convSD            string to double with optional limits check
   convSF            string to float with optional limits check
   convIS            integer to string with returned length
   convDS            double to string with specified digits of precision
   atofz             atof() accepting both '.' and ',' decimal points
   formatKBMB        format a byte count with specified precision and B/KB/MB/GB units
   
   Wildcard Functions
   ------------------
   MatchWild         match string to wildcard string (multiple * and ?)
   MatchWildCase     works like MatchWild() but ignores case
   SearchWild        wildcard file search (multiple * and ? in path or file name)
   SearchWildCase    works like SearchWild() but ignores case in file name
   zfind             find files matching a pattern. uses glob()

   Search and Sort Functions
   -------------------------
   bsearch           binary search of sorted list
   HeapSort          sort list of integer / float / double / records / pointers to records
   MemSort           sort records with multiple keys (data types and sequence)
   zmember           test if a value is a member of a set of values
   HashTab           hash table: add, delete, find, step through

   Misc Functions
   --------------
   zlist functions         list processing functions - array of string pointers
   random numbers          int and double random numbers with improved distributions
   spline1/2               cubic spline curve fitting function
   Qtext                   FIFO queue for text strings, dual thread access
   variance                compute variance for a list of numbers

   Application Admin Functions
   ---------------------------
   get_zprefix             /usr or /home/<user>
   get_zhomedir            /home/<user>/.appname or custom location
   get_zdatadir            app data files location
   get_zdocdir             app documentation files location
   get_zimagedir           app image files location

   zinitapp                initialize application folder and data files
   zabout                  popup application 'about' information
   zsetfont                set new application font
   widget_font_metrics     get font width and height for given widget
   get_zfilespec           get filespec for README, changelog, userguide, parameters ...
   showz_logfile           display application log file
   showz_textfile          show application text file (README, changelog, etc.)
   showz_docfile           show a document file topic and associated image
   audit_docfile           audit docfile for missing topics and bad links

   GTK Utility Functions
   ---------------------
   zmainloop               do main loop to process menu events, etc.
   zmainsleep              loop zmainloop and zsleep for designated time
   draw_context_create     get cairo drawing context for GDK window
   textwidget              text report, navigation, line editing
   create_menubar          menubar functions
   create_toolbar          toolbar functions
   create_stbar            statusbar functions
   create_popmenu          implement popup menus
   Vmenu                   vertical menu/toolbar in vertical packing box

   splcurve_init           set up a spline curve drawing area
   splcurve_adjust         mouse event function to manipulate curve nodes
   splcurve_addnode        add an anchor point to a curve
   splcurve_resize         resize drawing area if too small
   splcurve_draw           draw curve through nodes
   splcurve_generate       generate x/y table of values from curve
   splcurve_yval           get curve y-value for given x-value
   splcurve_load           load curve data from a saved file
   splcurve_save           save curve data to a file

   zdialog_new                create new zdialog
   zdialog_set_title          change a zdialog title
   zdialog_set_modal          set a zdialog to be modal
   zdialog_set_decorated      set a zdialog to be decorated or not
   zdialog_present            present a zdialog (visible and on top)
   zdialog_can_focus          set zdialog can or cannot have focus
   zdialog_set_focus          set focus on zdialog window or window + widget
   zdialog_add_widget         add widget to existing zdialog
   zdialog_valid              return 1/0 if zdialog is valid/invalid
   zdialog_find_widget        return widget from zdialog and widget name
   zdialog_gtkwidget          get GTK widget from zdialog and widget name
   zdialog_set_image          set image widget from GDK pixbuf
   zdialog_add_ttip           add a popup tool tip to a zdialog widget
   zdialog_set_group          set a common group for a set of radio buttons
   zdialog_resize             resize zdialog greater than initial size
   zdialog_put_data           put data into a zdialog widget of any type
   zdialog_get_data           get data from a zsialog widget of any type
   zdialog_set_limits         set new limits for numeric data entry widget
   zdialog_get_limits         get limits for numeric data entry widget
   zdialog_rescale            expand the scale around a neutral value
   zdialog_run                run the zdialog and send events to event function
   zdialog_widget_event       respond to zdialog widget events
   zdialog_focus_in_event     response handler for "focus-in-event" signal
   zdialog_activate_event     response handler for "activate" signal ('enter' key)
   zdialog_KB_press           respond to zdialog keyboard inputs
   zdialog_zspin_event        response function for "zspin" widget
   zdialog_copyfunc           copy widget data to clipboard
   zdialog_pastefunc          copy clipboard to widget with KB focus
   zdialog_delete_event       process zdialog delete event ([x] button)
   zdialog_send_event         send an event to an active zdialog
   zdialog_send_response      complete a zdialog and assign status
   zdialog_show               show or hide a zdialog window
   zdialog_destroy            destroy a zdialog (data remains available)
   zdialog_free               free zdialog memory (data is gone)
   zdialog_wait               wait for zdialog completion, get status
   zdialog_goto               put cursor at named widget
   zdialog_set_cursor         set zdialog cursor (e.g. busy)
   zdialog_stuff              stuff data into zdialog widget
   zdialog_labelfont          set label text with font
   zdialog_fetch              fetch data from zdialog widget
   zdialog_combo_clear        clear combo box entries
   zdialog_combo_popup        open combo box pick list
   zdialog_load_widgets       load zdialog widgets and curves from a file
   zdialog_save_widgets       save zdialog widgets and curves to a file
   zdialog_load_prev_widgets  load last-used widgets (for [prev] buttons)
   zdialog_save_last_widgets  save last-used widgets (for [prev] buttons)

   zdialog_geometry           load/save zdialog positions at app start/exit
   zdialog_set_position       set zdialog position: null mouse desktop parent save nn/nn
   zdialog_save_position      remember zdialog position relative to parent
   zdialog_save_inputs        save zdialog inputs when zdialog completed
   zdialog_load_inputs        retrieve prior zdialog input fields

   zdialog_text               popup zdialog to get N lines of text input from user
   zdialog_text1              popup zdialog to get one line of text input from user
   zdialog_password           popup zdialog to get a password entry (invisible)
   zdialog_choose             popup zdialog to show a message, select a button, return choice
   zdialog_choose2            popup zdialog, same as above with addition of KB inputs
   zdialog_edit_textfile      popup zdialog to edit a text file

   popup_report            popup window and scrolling text report
   popup_command           run a shell command with output in a popup window
   zmessageACK             popup message, printf format, wait for user ACK
   zmessageYN              popup message, printf format, wait for user Yes / No
   zmessage_post           popup message, printf format, show until killed
   poptext_screen          popup message at given absolute screen position
   poptext_mouse           popup message at current mouse position + offset
   poptext_window          popup message at given window position + offset
   poptext_widget          popup message at given widget position + offset
   poptext_killnow         kill popup message
   popup_picklist          popup picklist, return choice
   zgetfile                simplified file chooser zdialog
   zgetfolder              file chooser for folder, with create option
   print_image_file        zdialog to print an image file using GTK functions
   drag_drop_source        connect window as drag-drop source
   drag_drop_dest          connect window as drag-drop destination
   get_thumbnail           get thumbnail image for given image file
   zmakecursor             make a cursor from an image file (.png .jpg)
   gdk_pixbuf_rotate       rotate a pixbuf through any angle
   gdk_pixbuf_stripalpha   remove an alpha channel from a pixbuf
   text_pixbuf             create pixbuf containing text
   move_pointer            move the mouse pointer within a widget/window
   window_to_mouse         move a GtkWindow to the mouse position

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

namespace zfuncs
{
   GdkDisplay     *display;                                                      //  workstation (KB, mouse, screen)
   GdkScreen      *screen;                                                       //  screen, N monitors
   GdkDevice      *mouse;                                                        //  pointer device
   GtkSettings    *gtksettings = 0;                                              //  screen settings
   GtkWidget      *mainwin = 0;                                                  //  main window
   GtkTextView    *curr_textview_widget;                                         //  curr. GtkTextView widget
   ch          zcontact[] = "mkornelix@gmail.com";                               //  author contact
   ch          *build_date_time = __DATE__ " " __TIME__;                         //  build date and time
   ch          *progexe = 0;                                                     //  executable image file
   int         Floglevel = 1;                                                    //  0/1/2 = errs/infos/dialog inputs
   int         Fescape = 0;                                                      //  zdialog, escape key pressed
   int         monitor_ww, monitor_hh;                                           //  monitor dimensions
   int         appfontsize = 10;                                                 //  application font size
   ch          *appfont = "sans 10";                                             //  application font defaults
   ch          *appboldfont = "sans bold 10";
   ch          *appmonofont = "mono 10";
   ch          *appmonoboldfont = "mono bold 10";
   ch          zappname[40] = "undefined";                                       //  appname without version
   ch          zappvers[40] = "undefined";                                       //  appname-N.N
   ch          zprefix[200], zdatadir[200], zdocdir[200];                        //  app folders
   ch          zimagedir[200], zhomedir[200];
   ch          logfile[200];                                                     //  application log file
   pthread_t   tid_main = 0;                                                     //  main() thread ID
   int         vmenuclickposn;                                                   //  Vmenu image click posn. 0-100
   int         vmenuclickbutton;                                                 //  button: 1/2/3 = L/M/R mouse
   int         vmenustop;                                                        //  setupfunc() stop flag
   zdialog     *zdialog_list[zdialog_max];                                       //  active zdialog list
   int         zdialog_count = 0;                                                //  total zdialogs (new - free)
   float       splcurve_minx = 5;                                                //  min. anchor point dist, % scale
   ch          *zappcrash_context1 = 0, *zappcrash_context2 = 0;
}

using namespace zfuncs;


/********************************************************************************
   system-level utility functions
*********************************************************************************/

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

   zmalloc() zfree() zstrdup()
   These are wrappers for malloc() and free() with extra diagnostics.
   zmalloc() crashes with a message to standard output if the allocation fails,
   hence the caller need not check. zmalloc() allocates extra memory for sentinels
   placed before and after the returned memory space, and zfree() checks the
   sentinels for validity and crashes with a message if they don't match.
   The optional tag argument is also copied into the extra allocated space for use
   by zmalloc_report(). zmalloc_report() reports total allocated memory by tag to
   standard output. Allocation counts and bytes are listed for zmalloc() calls
   not yet matched by zfree() calls.

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

#define  zmalloc_extra 36
int64    zmalloc_tot = 0;
int      zmalloc_lock = 0;

void  zmalloc_tabulate(ch *tag, int64 cc);                                       //  private function


void * zmalloc(int64 cc, ch *tag)                                                //  bytes, tag
{
   double      memavail;
   static int  ftf = 1, memcheck = 1;
   double      mcc;

   while (! resource_lock(zmalloc_lock)) zsleep(0.001);

   ch          *OOMmessage = "                   \n"                             //  big and obvious
                             "  ---------------  \n"
                             "   OUT OF MEMORY   \n"
                             "  ---------------  \n";
   if (ftf) {                                                                    //  first call
      ftf = 0;
      memavail = availmemory();
      if (! memavail) memcheck = 0;                                              //  memory checking not possible, disable
   }

   if (cc <= 0) zappcrash("zmalloc: %lld bytes",cc);

   if (memcheck && cc > 1000) {                                                  //  large block
      mcc = cc;
      mcc = mcc / 1024 / 1024;                                                   //  requested memory, MB
      memavail = availmemory();                                                  //  avail. memory, MB
      if (memavail - mcc < 500) {
         Plog(0,"memory request for %.0f MB failed\n",mcc);
         zexit(1,OOMmessage);
         exit(-1);
      }
   }

   if (! tag) tag = "zmalloc notag";

   void *   maddr = malloc(cc + zmalloc_extra);     //  0             allocated memory with extra space
   int64    *pcc = (int64 *) maddr;                 //  0..8          caller byte count
   ch       *psen1 = (ch *) maddr + 8;              //  8..11         sentinel "sen1"
   ch       *ptag = (ch *) maddr + 12;              //  12..31        tag, < 20 chars.
   ch       *puser =  (ch *) maddr + 32;            //  32..B+31      user data, B chars.
   ch       *psen2 =  (ch *) puser + cc;            //  B+32..B+35    sentinel "sen2"

   if (! maddr) {
      zexit(1,OOMmessage);
      exit(-1);
   }

   *pcc = cc;
   strncpy(psen1,"sen1",4);                                                      //  set leading sentinel
   strncpy0(ptag,tag,20);                                                        //  set tag
   strncpy(psen2,"sen2",4);                                                      //  set following sentinel

   memset(puser,0,cc);                                                           //  clear allocation (force memory commit)

   zmalloc_tot += cc;
   zmalloc_tabulate(ptag,cc);                                                    //  track usage by tag

   resource_unlock(zmalloc_lock);
   return puser;
}


//  free memory allocated by zmalloc(). checks for overflow.

void zfree(void *puser)
{
   if (! puser) zappcrash("zfree: null address");

   void        *maddr = (ch *) puser - 32;
   int64       *pcc = (int64 *) maddr;
   ch          *psen1 = (ch *) maddr + 8;
   ch          *ptag = (ch *) maddr + 12;
   int64       cc = *pcc;
   ch          *psen2 = (ch *) puser + cc;

   while (! resource_lock(zmalloc_lock)) zsleep(0.001);

   if (strncmp("sen1",psen1,4) || strncmp("sen2",psen2,4))                       //  check sentinels
      zappcrash("zfree: sentinels clobbered");
   *psen1 = *psen2 = 0;                                                          //  destroy sentinels

   ch   * puser2 = (ch *) puser;                                                 //  clobber to detect use after free
   *puser2 = '*';

   zmalloc_tot -= cc;
   zmalloc_tabulate(ptag,-cc);                                                   //  track usage by tag

   free(maddr);                                                                  //  free memory (must be last)

   resource_unlock(zmalloc_lock);
   return;
}


//  private function. track how much memory is in use, per tag.
//  real tag capacity is about 80% of nominal 'zmhtcap'

#define  zmhtcap 500
HashTab     *zmalloc_hashtab = 0;
int64       zmalloc_count[zmhtcap];
int64       zmalloc_bytes[zmhtcap];

void zmalloc_tabulate(ch *ptag, int64 cc)
{
   int      ii;

   if (! zmalloc_hashtab) {
      zmalloc_hashtab = new HashTab(20,zmhtcap);
      memset(zmalloc_count, 0, zmhtcap * sizeof(int64));
      memset(zmalloc_bytes, 0, zmhtcap * sizeof(int64));
   }

   ii = zmalloc_hashtab->Find(ptag);
   if (ii < 0) ii = zmalloc_hashtab->Add(ptag);
   if (ii < 0) zappcrash("zmalloc hash table full");

   zmalloc_bytes[ii] += cc;
   if (cc > 0) ++zmalloc_count[ii];
   else  --zmalloc_count[ii];

   return;
}


//  report total memory allocated per tag - leak detection utility
//  GUI popup report

void zmalloc_report(void *vzd)
{
   int      count, ii, first = 1;
   int64    cc;
   ch       tag[20];
   zdialog  *zd = (zdialog *) vzd;

   popup_report_write(zd,0,"zmalloc total memory: %lld \n",zmalloc_tot);

   while (true)
   {
      ii = zmalloc_hashtab->GetNext(first,tag);
      if (ii < 0) break;
      ii = zmalloc_hashtab->Find(tag);
      if (ii < 0) zappcrash("zmalloc hash table bug: %s",tag);
      cc = zmalloc_bytes[ii];
      count = zmalloc_count[ii];
      if (cc == 0) continue;
      popup_report_write(zd,0,"  %-20s  %8d  %lld \n",tag,count,cc);
   }

   popup_report_write(zd,0,"\n");
   return;
}


//  report total memory allocated per tag - leak detection utility
//  report only tags with increased memory consumption since prior report

void zmalloc_growth(void *vzd)
{
   int         count, ii, first = 1;
   int64       cc;
   ch          tag[20];
   zdialog     *zd = (zdialog *) vzd;

   static int     pne = 0;                                                       //  table of prior tag and cc values
   static ch      *ptag[1000];
   static int64   pcc[1000];

   popup_report_write(zd,0,"zmalloc total memory: %lld \n",zmalloc_tot);

   while (true)                                                                  //  loop all tags in table
   {
      ii = zmalloc_hashtab->GetNext(first,tag);
      if (ii < 0) break;
      ii = zmalloc_hashtab->Find(tag);
      if (ii < 0) zappcrash("zmalloc hash table bug: %s",tag);
      cc = zmalloc_bytes[ii];                                                    //  memory allocation for tag
      count = zmalloc_count[ii];                                                 //  zmalloc/zfree calls for tag
      if (cc == 0) continue;                                                     //  net memory = 0, skip

      for (ii = 0; ii < pne; ii++)                                               //  find prior allocation for tag
         if (strmatch(tag,ptag[ii])) break;
      if (ii == pne) {
         ptag[ii] = strdup(tag);                                                 //  new tag, add to table
         pcc[ii] = cc;
         pne++;
      }

      if (cc <= pcc[ii]) continue;                                               //  current <= prior allocation, skip

      popup_report_write(zd,0,"  %-20s  %8d  %lld \n",tag,count,cc);             //  report increased allocation
      pcc[ii] = cc;                                                              //  new high-water allocation
   }

   popup_report_write(zd,0,"\n");
   return;
}


//  test if a given about of free memory is available
//  return 1 if OK, return 0 if NO.

int zmalloc_test(int64 cc)
{
   double      memavail, mb;

   mb = cc / 1024 / 1024;
   memavail = availmemory();                                                     //  avail. memory, MB
   memavail -= mb;
   if (memavail > 300) return 1;                                                 //  > 300 MB remaining, return OK
   Plog(0,"planned memory allocation of %.0f MB failed \n",mb);
   return 0;                                                                     //  not OK
}


//  get real memory in MB units
//  typical < 0.1 milliseconds

double realmemory()
{
   FILE     *fid;
   ch       buff[100], *pp;
   double   rmem = 0;

   fid = fopen("/proc/meminfo","r");
   if (! fid) return 0;

   while (true)
   {
      pp = fgets(buff,100,fid);
      if (! pp) break;
      if (strmatchN(pp,"MemAvailable:",13)) {                                    //  free + file cache
         rmem = atof(pp+13) / 1024;
         break;
      }
   }

   fclose(fid);
   return rmem;
}


//  get available memory in MB units (includes swap space)
//  typical < 0.1 milliseconds

double availmemory()
{
   FILE     *fid;
   ch       buff[100], *pp;
   double   avmem = 0;
   int      Ngot = 0;

   fid = fopen("/proc/meminfo","r");
   if (! fid) return 0;

   while (true)
   {
      pp = fgets(buff,100,fid);
      if (! pp) break;
      if (strmatchN(pp,"MemAvailable:",13)) {                                    //  free + file cache
         avmem += atof(pp+13) / 1024;
         if (++Ngot == 2) break;
      }

      if (strmatchN(pp,"SwapFree:",9)) {                                         //  swapfile free
         avmem += atof(pp+9) / 1024;
         if (++Ngot == 2) break;
      }
   }

   fclose(fid);
   return avmem;
}


//  duplicate string in allocated memory, with additional space at end

ch * zstrdup(ch *zstring, ch *tag, int addcc)
{
   if (! zstring) zappcrash("zstrdup() null arg");
   if (! tag) tag = "zstrdup notag";
   ch   *pp = (ch *) zmalloc(strlen(zstring) + 1 + addcc, tag);                  //  add additional chars, clear
   strcpy(pp,zstring);
   return pp;
}


//  replace zstring with string + added cc

int zstrcopy(ch *&zstring, ch *string, ch *tag, int addcc)
{
   if (! tag) tag = "zstrcopy notag";
   if (zstring == string) zstring = 0;                                           //  if same string, make a duplicate
   if (zstring) zfree(zstring);
   int cc = strlen(string) + 1 + addcc;
   zstring = (ch *) zmalloc(cc,tag);
   strcpy(zstring,string);
   return cc;
}


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

//  add message to stdout log file if Floglevel >= message level
//  flush every output immediately even if stdout is a file
//  use lev = 0 for mandatory error message
//      lev = 1 for informative message
//      lev = 2 for everything

void Plog(int lev, ch *format, ...)
{
   if (lev > Floglevel) return;

   va_list  arglist;
   va_start(arglist,format);
   vprintf(format,arglist);
   va_end(arglist);
   fflush(stdout);
   return;
}


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

//  output a popup message not requiring GTK

void xmessage(ch *message)
{
   ch       command[400];
   ch       *font = "-*-*-*-*-*--*-200-*-*-*-*-*-*";                             //  big font

   Plog(0,"%s: \n %s \n",zappname,message);
   snprintf(command,400,"xmessage -font \'%s\' -center \" %s: \n %s \" ",
                              font, zappname, message);
   int err = system(command);                                                    //  do not use zshell
   if (err) return;                                                              //  avoid gcc warning
   return;
}


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

//  Output a status or error message and kill all processes in the process group.
//  killpg(0,SIGKILL) kills all processes, including the caller.
//  if 'popup' true, popup an xmessage window with error message.

void zexit(int popup, ch *errmess, ...)
{
   va_list  arglist;
   ch       mess[1000];

   if (errmess) {                                                                //  output error message
      va_start(arglist,errmess);
      vsnprintf(mess,1000,errmess,arglist);
      Plog(0,"zexit: %s\n",mess);
      if (popup) xmessage(mess);                                                 //  popup message
   }
   else Plog(0,"zexit\n");

   killpg(0,SIGKILL);                                                            //  kill all processes in group
   sleep(1);                                                                     //  wait here to die
   exit(-1);
}


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

//  produce a backtrace dump to stdout

void zbacktrace()
{
   int      nstack = 100;
   void     *stacklist[100];

   nstack = backtrace(stacklist,nstack);                                         //  get backtrace data
   if (nstack > 100) nstack = 100;
   backtrace_symbols_fd(stacklist,nstack,STDOUT_FILENO);                         //  backtrace records to STDOUT

   return;
}


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

//  Write an error message and backtrace dump to a file and to a popup window.
//  Error message works like printf().
//  Depends on program addr2line() in binutils package.

void zappcrash(ch *format, ... )
{
   static int     crash = 0;
   struct utsname unbuff;
   va_list        arglist;
   FILE           *fid1, *fid2, *fid3;
   int            fd, ii, err, cc, nstack = 100;
   int            Flinenos = 1;
   void           *stacklist[100];
   ch             OS1[60] = "?", OS2[60] = "?", OS3[60] = "?";
   ch             message[300], progexe[300];
   ch             buff1[300], buff2[300], hexaddr[20];
   ch             *arch, *pp1, *pp2, dlim, *pfunc;

   if (crash++) return;                                                          //  re-entry or multiple threads crash

   va_start(arglist,format);
   vsnprintf(message,300,format,arglist);
   va_end(arglist);

   uname(&unbuff);                                                               //  get cpu arch. 32/64 bit
   arch = unbuff.machine;
   fid1 = popen("lsb_release -d","r");                                           //  get Linux flavor and release
   if (fid1) {
      ii = fscanf(fid1,"%s %s %s",OS1,OS2,OS3);
      pclose(fid1);
   }

   xmessage("A fatal error has occurred. \n"                                     //  popup message
            " See zappcrash file in home folder.");

   Plog(0,"\n*** zappcrash: %s %s %s %s %s %s \n",
               arch, OS2, OS3, zappvers, build_date_time, message);
   Plog(0,"*** zappcrash context: %s | %s \n",zappcrash_context1, zappcrash_context2);

   nstack = backtrace(stacklist,nstack);                                         //  get backtrace data
   if (nstack <= 0) zexit(0,"zappcrash backtrace() failure");
   if (nstack > 100) nstack = 100;

   fid1 = fopen("zbacktrace","w");                                               //  open backtrace data output file
   if (! fid1) zexit(0,"zappcrash fopen() failure");

   fd = fileno(fid1);
   backtrace_symbols_fd(stacklist,nstack,fd);                                    //  write backtrace data
   fclose(fid1);                                                                 //  (use of malloc() is avoided)

   fid1 = fopen("zbacktrace","r");                                               //  open backtrace data file
   if (! fid1) zexit(0,"zappcrash fopen() failure");

   fid2 = fopen("zappcrash","w");                                                //  open zappcrash output file
   if (! fid2) zexit(0,"zappcrash fopen() failure");

   fprintf(fid2,"\n*** zappcrash: %s %s %s %s %s %s \n",
                     arch, OS2, OS3, zappvers, build_date_time, message);
   fprintf(fid2,"*** zappcrash context: %s | %s \n",zappcrash_context1, zappcrash_context2);
   fprintf(fid2,"*** please send this crash report to mkornelix@gmail.com *** \n"
                "*** if possible, please explain how to repeat this problem *** \n");

   cc = readlink("/proc/self/exe",progexe,300);                                  //  get own program path
   if (cc > 0) progexe[cc] = 0;                                                  //  readlink() quirk
   else {
      fprintf(fid2,"progexe not available \n");
      Flinenos = 0;
   }

   err = zshell(0,"which addr2line >> /dev/null");                               //  check if addr2line() available
   if (err) Flinenos = 0;

   for (ii = 0; ii < nstack; ii++)                                               //  loop backtrace records
   {
      pp1 = pp2 = 0;
      fgets_trim(buff1,300,fid1);                                                //  read backtrace line
      if (! Flinenos) goto output;
      pfunc = 0;
      pp1 = strstr(buff1,"+0x");                                                 //  new format (+0x12345...)
      if (pp1) pp2 = strchr(pp1,')');
      else {
         pp1 = strstr(buff1,"[0x");                                              //  old format [0x12345...]
         if (pp1) pp2 = strchr(pp1,']');
      }
      if (! pp1 || ! pp2) goto output;                                           //  cannot parse
      dlim = *pp2;
      *pp2 = 0;
      strncpy0(hexaddr,pp1+1,20);
      *pp2 = dlim;
      snprintf(buff2,300,"addr2line -i -e %s %s",progexe,hexaddr);               //  convert to source program
      fid3 = popen(buff2,"r");                                                   //    and line number
      if (! fid3) goto output;
      pfunc = fgets(buff2,300,fid3);
      pclose(fid3);
      if (! pfunc) goto output;
      cc = strlen(pfunc);
      if (cc < 10) goto output;
      if (pfunc[cc-1] < ' ') pfunc[cc-1] = 0;                                    //  remove tailing \n if present
      strncatv(buff1,300,"\n--- ",pfunc,null);
   output:
      fprintf(fid2,"%s \n",buff1);                                               //  output
   }

   fclose(fid1);
   fclose(fid2);

   zshell(0,"rm zbacktrace");                                                    //  remove backtrace file
   zshell(0,"cat zappcrash");                                                    //  add zappcrash to log file
   zshell(0,"rm zappcrash");                                                     //  remove zappcrash file
   if (*logfile == '/') zshell(0,"cp -f %s $HOME/zappcrash",logfile);            //  copy log file to $HOME/zappcrash
   zexit(0,"Zexit zappcrash");                                                   //  quit
}


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

//  application initialization function to catch some bad news signals
//  the signal handler calls zappcrash() to output a backtrace dump and exit

void catch_signals()
{
   void sighandler(int signal);
   struct sigaction  sigact;

   sigact.sa_handler = sighandler;
   sigemptyset(&sigact.sa_mask);
   sigact.sa_flags = 0;

   sigaction(SIGTERM,&sigact,0);
   sigaction(SIGSEGV,&sigact,0);
   sigaction(SIGILL,&sigact,0);                                                  //  man page says cannot be caught
   sigaction(SIGFPE,&sigact,0);
   sigaction(SIGBUS,&sigact,0);
   sigaction(SIGABRT,&sigact,0);                                                 //  heap or stack corruption
   return;
}


//  catch fatal signals and produce backtrace dumps on-screen

void sighandler(int signal)
{
   cch  *signame = "unknown";

   if (signal == SIGTERM) zexit(0,"TERMINATED");
   if (signal == SIGKILL) zexit(0,"KILLED");
   if (signal == SIGSEGV) signame = "segment fault";
   if (signal == SIGILL) signame = "illegal operation";
   if (signal == SIGFPE) signame = "arithmetic exception";
   if (signal == SIGBUS) signame = "bus error (bad memory)";
   if (signal == SIGABRT) signame = "abort";

   zappcrash("fatal signal: %s",signame);
   exit(0);
}


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

//  Implement the TRACE macro.
//  Trace program execution by function and source code line number.
//  tracedump() dumps last 50 uses of TRACE macro, latest first.

namespace tracenames
{
   ch    filebuff[50][100];                                                      //  last 50 TRACE calls
   ch    funcbuff[50][60];
   int   linebuff[50];
   void  *addrbuff[50];
   int   ii, ftf = 1;
};


//  Args are source file, source function name, source code line number,
//  caller address. These all come from the GCC compiler and TRACE macro.

void trace(ch *file, ch *func, int line, void *addr)
{
   using namespace tracenames;

   if (ftf) {
      ftf = 0;
      for (ii = 0; ii < 50; ii++) {
         filebuff[ii][99] = 0;
         funcbuff[ii][39] = 0;
         linebuff[ii] = 0;
         addrbuff[ii] = 0;
      }
      ii = 0;
   }

   if (line == linebuff[ii] &&
      strmatch(func,funcbuff[ii])) return;                                       //  same as last call, don't duplicate

   if (++ii > 49) ii = 0;                                                        //  add data to list
   strncpy(&filebuff[ii][0],file,99);
   strncpy(&funcbuff[ii][0],func,39);
   linebuff[ii] = line;
   addrbuff[ii] = addr;
   return;
}


//  dump trace records to STDOUT

void tracedump()
{
   using namespace tracenames;

   FILE     *fid;
   int      kk;

   Plog(0," *** tracedump *** \n");

   kk = ii;
   while (linebuff[kk]) {
      Plog(0,"TRACE %s %s %d %p \n",&filebuff[kk][0],
              &funcbuff[kk][0],linebuff[kk],addrbuff[kk]);
      if (--kk == ii) break;
   }

   fid = fopen("tracedump","w");
   if (! fid) {
      perror("tracedump fopen() failure \n");
      return;
   }

   fprintf(fid, " *** tracedump *** \n");

   kk = ii;
   while (linebuff[kk]) {
      fprintf(fid, "TRACE %s %s %d %p \n",&filebuff[kk][0],
                    &funcbuff[kk][0],linebuff[kk],addrbuff[kk]);
      if (--kk == ii) break;
   }

   fclose(fid);
   return;
}


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

//  restart the current program as root user (after sudo success)
//  argc and argv are the original command line arguments

void beroot(int argc, ch *argv[])
{
   int      err, cc;
   ch       command[500], *args;

   if (getuid() == 0) return;                                                    //  already root

   cc = readlink("/proc/self/exe",command,500);                                  //  use own program path
   if (cc > 0) command[cc] = 0;                                                  //  readlink() quirk
   else {
      Plog(0,"beroot() readlink failed \n");
      exit(1);
   }

   args = combine_argvs(argc,argv,1);                                            //  get "arg1 arg2 ..." in one string
   strncatv(command,500," ",args,null);
   err = runroot(command);                                                       //  start new process
   exit(err);                                                                    //  exit old process (after new process exit)
}


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

//  run a command or program as root user
//  command:  shell command or filespec of the program to start
//  return:    0  OK
//             1  password not entered
//             N  other error

int runroot(ch *command)
{
   int         err;
   ch          *pw, command2[500];
   static ch   rpw[100] = "";

   Plog(0,"runroot: %s \n",command);
   
   if (getuid() == 0)                                                            //  already root                          24.20
   {
      err = zshell("ack",command);                                               //  run command (and wait for completion)
      return err;
   }
      
   if (! *rpw) 
   {
      pw = zdialog_password(0,"enter root password",0);                          //  get password from user
      if (! pw || ! pw[0]) return 1;
      strncpy0(rpw,pw,100);                                                      //  save for next time                    24.20
   }
   
   snprintf(command2,500,"echo %s | sudo -S %s &\n",rpw,command);                //  sudo with password and user command
   err = zshell("ack",command2);                                                 //  run command (and wait for completion)
   return err;
}


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

//  ch * combine_argvs(int argc, ch *argv[], Nth)
//    combine argv[ii] elements from Nth to last
//    returned char string has one blank between each element

ch * combine_argvs(int argc, ch *argv[], int Nth)
{
   int          ii, ccv, outcc = 0;
   static ch    output[XFCC];

   for (ii = Nth; ii < argc; ii++)
   {
      ccv = strlen(argv[ii]);
      if (outcc + ccv > XFCC - 2) return 0;
      strcpy(output+outcc,argv[ii]);
      outcc += ccv;
      output[outcc] = ' ';
      outcc++;
   }

   outcc--;
   output[outcc] = 0;
   return output;
}


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

//  get time in real seconds
//  theoretically uses a precise system clock but the precision is poor

double get_seconds()
{
   timespec    time1;
   double      secs;

   clock_gettime(CLOCK_MONOTONIC_RAW,&time1);
   secs = time1.tv_sec;
   secs += time1.tv_nsec * 0.000000001;
   return secs;
}


//  get time in real seconds from timespec struct

double get_seconds(timespec *ts)
{
   double   secs;

   secs = ts->tv_sec;
   secs += ts->tv_nsec * 0.000000001;
   return secs;
}


//  get file mod time in real seconds

double get_modtime(char *file)
{
   STATB    statB;
   int      err;

   err = stat(file,&statB);
   if (err) return 0;
   return get_seconds(&statB.st_mtim);
}


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

//  log elapsed time since last log point
//  logtime_init(text)     initialize timer
//  logtime(text)          report time since last logtime() call

namespace logtime_names
{
   timespec    time1, time2;
   double      elapsed;
}

void logtime_init(ch *text)
{
   using namespace logtime_names;

   printf("logtime init: %s\n",text);
   clock_gettime(CLOCK_MONOTONIC_RAW,&time1);
   return;
}

void logtime(ch *text)
{
   using namespace logtime_names;

   clock_gettime(CLOCK_MONOTONIC_RAW,&time2);
   elapsed = time2.tv_sec - time1.tv_sec;
   elapsed += 0.000000001 * (time2.tv_nsec - time1.tv_nsec);
   time1 = time2;
   printf("logtime %s: %.8f \n",text,elapsed);
   return;
}


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

//  start a timer or get elapsed time with millisecond resolution.

void start_timer(double &time0)
{
   timeval  timev;

   gettimeofday(&timev,0);
   time0 = timev.tv_sec + 0.000001 * timev.tv_usec;
   return;
}

double get_timer(double &time0)
{
   timeval  timev;
   double   time;

   gettimeofday(&timev,0);
   time = timev.tv_sec + 0.000001 * timev.tv_usec;
   return time - time0;
}


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

//  start a process CPU timer or get elapsed process CPU time
//  returns seconds with millisecond resolution

void start_CPUtimer(double &time0)
{
   time0 = CPUtime();
   return;
}

double get_CPUtimer(double &time0)
{
   return CPUtime() - time0;
}


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

//  get elapsed CPU time used by current process
//  returns seconds with millisecond resolution

double CPUtime()
{
   clock_t ctime = clock();
   double dtime = ctime / 1000000.0;
   return dtime;
}


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

//  get real memory used by current process, MB

int memused()                                                                    //  24.20
{
   ch       buff1[100], buff2[1000];
   ch       *pp = 0;
   FILE     *fid;
   double   mem;
   int      MB, pagesize;
   int      mega = 1024 * 1024;
   
   snprintf(buff1,100,"/proc/self/stat");                                        //  read file /proc/self/stat
   fid = fopen(buff1,"r");
   if (fid) {
      pp = fgets(buff2,1000,fid);
      fclose(fid);
   }

   MB = 0;
   
   if (pp) {
      pp = strchr(pp,')');                                                       //  closing ')' after (short) filename
      if (pp) {
         parseprocrec(pp+1,22,&mem,null);                                        //  get real memory
         pagesize = sysconf(_SC_PAGESIZE);                                       //  system page size
         MB = mem * pagesize / mega + 0.5;
      }
   }

   return MB;
}


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

//  get process CPU time and block I/O count
//  returns 0 = OK, 1 = error

int proc_resources(double &cpu, double &bio)
{
   struct rusage  usage;
   double         utime, stime, inbio, outbio;
   int            err;

   err = getrusage(RUSAGE_SELF,&usage);
   if (err) return 1;
   utime = usage.ru_utime.tv_sec + 0.000001 * usage.ru_utime.tv_usec;
   stime = usage.ru_stime.tv_sec + 0.000001 * usage.ru_stime.tv_usec;
   inbio = usage.ru_inblock;
   outbio = usage.ru_oublock;
   cpu = utime + stime;
   bio = inbio + outbio;
   return 0;
}


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

//  convert a time_t date/time (e.g. st_mtime from stat() call)
//    into a compact date/time format "yyyymmddhhmmss"

void compact_time(time_t DT, ch *compactDT)
{
   struct tm   *fdt;
   int         year, mon, day, hour, min, sec;

   fdt = localtime(&DT);

   year = fdt->tm_year + 1900;
   mon = fdt->tm_mon + 1;
   day = fdt->tm_mday;
   hour = fdt->tm_hour;
   min = fdt->tm_min;
   sec = fdt->tm_sec;

   compactDT[0] = year / 1000 + '0';
   compactDT[1] = (year % 1000) / 100 + '0';
   compactDT[2] = (year % 100) / 10 + '0';
   compactDT[3] = year % 10 + '0';
   compactDT[4] = mon / 10 + '0';
   compactDT[5] = mon % 10 + '0';
   compactDT[6] = day / 10 + '0';
   compactDT[7] = day % 10 + '0';
   compactDT[8] = hour / 10 + '0';
   compactDT[9] = hour % 10 + '0';
   compactDT[10] = min / 10 + '0';
   compactDT[11] = min % 10 + '0';
   compactDT[12] = sec / 10 + '0';
   compactDT[13] = sec % 10 + '0';
   compactDT[14] = 0;

   return;
}


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

//  convert a time_t date/time (e.g. st_mtime from stat() call)
//    into a pretty date/time format "yyyy-mm-dd hh:mm:ss"

void pretty_datetime(time_t DT, ch *prettyDT)
{
   struct tm   *fdt;
   int         year, mon, day, hour, min, sec;

   fdt = localtime(&DT);

   year = fdt->tm_year + 1900;
   mon = fdt->tm_mon + 1;
   day = fdt->tm_mday;
   hour = fdt->tm_hour;
   min = fdt->tm_min;
   sec = fdt->tm_sec;

   prettyDT[0] = year / 1000 + '0';
   prettyDT[1] = (year % 1000) / 100 + '0';
   prettyDT[2] = (year % 100) / 10 + '0';
   prettyDT[3] = year % 10 + '0';
   prettyDT[4] = '-';
   prettyDT[5] = mon / 10 + '0';
   prettyDT[6] = mon % 10 + '0';
   prettyDT[7] = '-';
   prettyDT[8] = day / 10 + '0';
   prettyDT[9] = day % 10 + '0';
   prettyDT[10] = ' ';
   prettyDT[11] = hour / 10 + '0';
   prettyDT[12] = hour % 10 + '0';
   prettyDT[13] = ':';
   prettyDT[14] = min / 10 + '0';
   prettyDT[15] = min % 10 + '0';
   prettyDT[16] = ':';
   prettyDT[17] = sec / 10 + '0';
   prettyDT[18] = sec % 10 + '0';
   prettyDT[19] = 0;

   return;
}


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

//  seconds since 1970 (double) <--> year/mon/day/hour/min/secs (int[6])

void secs_datetime(double secs, int datetime[6])
{
   time_t   tsecs = secs;
   tm       *tmx;

   tmx = localtime(&tsecs);
   datetime[0] = tmx->tm_year + 1900;
   datetime[1] = tmx->tm_mon + 1;
   datetime[2] = tmx->tm_mday;
   datetime[3] = tmx->tm_hour;
   datetime[4] = tmx->tm_min;
   datetime[5] = tmx->tm_sec;
   return;
}


void datetime_secs(int datetime[6], double *secs)
{
   time_t   tsecs;
   tm       tmx;

   tmx.tm_year = datetime[0] - 1900;
   tmx.tm_mon  = datetime[1] - 1;
   tmx.tm_mday = datetime[2];
   tmx.tm_hour = datetime[3];
   tmx.tm_min  = datetime[4];
   tmx.tm_sec  = datetime[5];
   tmx.tm_isdst = -1;

   tsecs = mktime(&tmx);
   *secs = tsecs;
   return;
}


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

//  Read and parse /proc file with records formatted "parmname xxxxxxx"
//  Find all requested parameters and return their numeric values

int parseprocfile(ch *pfile, ch *pname, double *value, ...)                      //  EOL = 0
{
   FILE        *fid;
   va_list     arglist;
   ch          buff[1000];
   ch          *pnames[20];
   double      *values[20];
   int         ii, fcc, wanted, found;

   pnames[0] = pname;                                                            //  1st parameter
   values[0] = value;
   *value = 0;

   va_start(arglist,value);

   for (ii = 1; ii < 20; ii++)                                                   //  get all parameters
   {
      pnames[ii] = va_arg(arglist,ch *);
      if (! pnames[ii] || pnames[ii] == (ch *) 0x100000000) break;               //  ARM bug
      values[ii] = va_arg(arglist,double *);
      *values[ii] = 0;                                                           //  initialize to zero
   }

   va_end(arglist);

   if (ii == 20) zappcrash("parseProcFile, too many fields");
   wanted = ii;
   found = 0;

   fid = fopen(pfile,"r");                                                       //  open /proc/xxx file
   if (! fid) return 0;

   while ((fgets(buff,999,fid)))                                                 //  read record, "parmname nnnnn"
   {
      for (ii = 0; ii < wanted; ii++)
      {                                                                          //  look for my fields
         fcc = strlen(pnames[ii]);
         if (strmatchN(buff,pnames[ii],fcc)) {
            *values[ii] = atof(buff+fcc);                                        //  return value
            found++;
            break;
         }
      }

      if (found == wanted) break;                                                //  stop when all found
   }

   fclose(fid);
   return found;
}


//  Parse /proc record of the type  "xxx xxxxx xxxxx xxxxxxxx xxx"
//  Return numeric values for requested fields (starting with 1)

int parseprocrec(ch *prec, int field, double *value, ...)                        //  EOL = 0
{
   va_list     arglist;
   int         xfield = 1, found = 0;

   va_start(arglist,value);

   while (*prec == ' ') prec++;                                                  //  skip leading blanks

   while (field > 0)
   {
      while (xfield < field)                                                     //  skip to next wanted field
      {
         prec = strchr(prec,' ');                                                //  find next blank
         if (! prec) break;
         while (*prec == ' ') prec++;                                            //  skip multiple blanks
         xfield++;
      }

      if (! prec) break;
      *value = atof(prec);                                                       //  convert, return double
      found++;

      field = va_arg(arglist,int);                                               //  next field number
      if (! field || field == (int) 0x100000000) break;                          //  ARM bug
      value = va_arg(arglist,double *);                                          //  next output double *
   }

   while (field > 0)
   {
      *value = 0;                                                                //  zero values not found
      field = va_arg(arglist,int);
      value = va_arg(arglist,double *);
   }

   va_end(arglist);
   return found;
}


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

//  Get processor performance and efficiency core counts (SMP counts).
//  Return status: 0 = success, +N = error

int get_smp_counts(int &Pcores, int &Ecores)
{
   FILE     *fid;
   int      Nthreads, Nsockets;
   ch       *pp, buff[100] = "";

   Pcores = Ecores = 0;
   fid = popen("lscpu | grep 'CPU(s):'","r");
   if (! fid) goto erret;
   pp = fgets(buff,100,fid);
   pclose(fid);
   if (! pp || ! strmatchN(pp,"CPU(s):",7)) goto erret;
   Nthreads = atoi(pp+8);
   if (Nthreads < 1) goto erret;

   fid = popen("lscpu | grep 'Core(s) per socket:'","r");
   if (! fid) goto erret;
   pp = fgets(buff,100,fid);
   pclose(fid);
   if (! pp || ! strmatchN(pp,"Core(s) per socket:",19)) goto erret;
   Nsockets = atoi(pp+20);
   if (Nsockets < 1) goto erret;

   Pcores = Nthreads - Nsockets;
   Ecores = Nthreads - 2 * Pcores;
   if (Pcores < 1 || Ecores < 0) goto erret;
   if (Pcores > 64 || Ecores > 128) goto erret;
   return 0;

erret:
   Plog(0,"get_smp_counts() lscpu failed \n");
   return 1;
}


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

//  get current CPU temperature
//  returns 0 if cannot find

int coretemp()                                                                   //  use package temp
{
   FILE           *fid;
   static int     ftf = 1, zone, temp;
   static ch      Tfile[200];
   ch             buff[200], *pp;

   if (ftf)                                                                      //  first call, setup
   {                                                                             //  dump files ".../thermal_zone*/type"
      ftf = 0;
      fid = popen("cat /sys/class/thermal/thermal_zone*/type","r");              //  find file containing "pkg_temp"
      if (! fid) return 0;
      for (zone = 0; ; zone++) {
         pp = fgets(buff,200,fid);
         if (! pp) break;
         pp = strstr(pp,"pkg_temp");
         if (pp) break;
      }
      pclose(fid);                                                               //  ignore 'broken pipe' status           24.20

      if (! pp) {                                                                //  failed
         zone = -1;
         return 0;
      }
      snprintf(Tfile,200,"cat /sys/class/thermal/thermal_zone%d/temp",zone);     //  corresp. file ".../thermal_zone*/temp"
   }

   if (zone < 0) return 0;                                                       //  setup call failed

   fid = popen(Tfile,"r");                                                       //  read temp file
   if (! fid) return 0;
   pp = fgets(buff,200,fid);
   pclose(fid);
   if (! pp) return 0;
   temp = atoi(pp) / 1000;                                                       //  get temp, deg. C x 1000
   return temp;
}


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

//  get current temperature for given disk, e.g. "/dev/sda"
//  depends on "smartctl" command from package smartmontools

int disktemp(ch *disk)
{
   int         id, temp;
   ch          *pp, *pp2;
   ch          buff[200], command[100];
   FILE        *ffid;

   temp = 0;
   pp2 = 0;
   snprintf(command,100,"smartctl -A %s",disk);
   ffid = popen(command,"r");
   if (! ffid) return 0;

   while (true) {
      pp = fgets(buff,200,ffid);                                                 //  revised for smartctl report
      if (! pp) break;                                                           //    format changes
      if (strmatchN(pp,"ID#",3)) pp2 = strstr(pp,"RAW_VALUE");
      id = atoi(pp);
      if (id != 190 && id != 194) continue;                                      //  Airflow Temp. or Temp.
      if (! pp2) continue;
      temp = atoi(pp2);
      if (temp < 10 || temp > 99) temp = 0;
      break;
   }

   pclose(ffid);
   return temp;
}


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

//  sleep for specified time in seconds (double)
//  signals can cause early return

void zsleep(double dsecs)
{
   unsigned    isecs, nsecs;
   timespec    tsecs;

   if (dsecs <= 0) return;
   isecs = unsigned(dsecs);
   nsecs = unsigned(1000000000.0 * (dsecs - isecs));
   tsecs.tv_sec = isecs;
   tsecs.tv_nsec = nsecs;
   nanosleep(&tsecs,null);
   return;
}


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

//  loop for specified time in seconds (double)

void zloop(double dsecs)
{
   double  time0, time1;

   if (dsecs <= 0) return;
   time0 = get_seconds();
   time1 = time0 + dsecs;
   while (get_seconds() < time1) continue;
   return;
}


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

//  spinlock() is a simply way for a process to protect a code block from
//  concurrent execution by more than one thread, including the main() thread.
//  CANNOT BE USED for coroutines within one thread, e.g. GTK main loop.
//
//  spinlock(1);
//    ...  protected code           //  only one thread at a time can be in here
//  spinlock(0);
//
//  will deadlock if already locked by same thread

pthread_mutex_t spinmutex = PTHREAD_MUTEX_INITIALIZER;

void spinlock(int lock)
{
   if (lock) mutex_lock(&spinmutex);
   else mutex_unlock(&spinmutex);
   return;
}


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

//  Lock or unlock a multi-process multi-thread resource.
//  Only one process/thread may possess a given lock.
//  A reboot or process exit or crash releases the lock.
//  lockfile is typically "/tmp/filename" and does not have to exist
//
//  fd = global_lock(lockfile);
//    ...   protected code             //  only one process/thread at a time
//  global_unlock(fd,lockfile);


int global_lock(ch *lockfile)
{
   int       err, fd;

   while (true)                                                                  //  loop until success
   {
      fd = open(lockfile,O_RDWR|O_CREAT,0666);                                   //  open the lock file
      if (fd < 0) zappcrash("global_lock() %s",strerror(errno));
      err = flock(fd,LOCK_EX);                                                   //  request exclusive lock
      if (! err) return fd + 1;                                                  //  return value >= 1
      close(fd);                                                                 //  failed
      zsleep(0.001);                                                             //  wait a bit and try again
   }
}

void global_unlock(int fd, ch *lockfile)
{
   int err = close(fd-1);
   if (err < 0) zappcrash("global_unlock() %s",strerror(errno));
   return;
}


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

//  lock or unlock a resource
//  does not spin or wait for resource.
//  usable within or across threads in one process.
//  CANNOT BE USED for coroutines within one thread, e.g. GTK main loop.
//  return 0 if already locked, otherwise lock and return 1.

mutex_t resource_lock_lock = PTHREAD_MUTEX_INITIALIZER;

int resource_lock(int &resource)
{
   if (resource) return 0;                                                       //  locked

   mutex_lock(&resource_lock_lock);
   if (resource) {
      mutex_unlock(&resource_lock_lock);                                         //  locked
      return 0;
   }
   resource = 1;
   mutex_unlock(&resource_lock_lock);
   return 1;                                                                     //  locked OK
}

//  unlock a locked resource

void resource_unlock(int &resource)
{
   mutex_lock(&resource_lock_lock);
   if (resource != 1) zappcrash("resource not locked");                          //  not locked
   resource = 0;                                                                 //  unlock
   mutex_unlock(&resource_lock_lock);
   return;
}


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

//  Safely access and update parameters from multiple threads.
//  A mutex lock is used to insure one thread at a time has access to the parameter.
//  Many parameters can be used but there is only one mutex lock.
//  CANNOT BE USED for coroutines within one thread, e.g. GTK main loop.

mutex_t zget_lock = PTHREAD_MUTEX_INITIALIZER;

int zget_locked(int &param)                                                      //  lock and return parameter
{                                                                                //  (wait if locked)
   mutex_lock(&zget_lock);
   return param;
}

void zput_locked(int &param, int value)                                          //  set and unlock parameter
{
   param = value;
   mutex_unlock(&zget_lock);
   return;
}

int zadd_locked(int &param, int incr)                                            //  lock, increment, unlock, return
{
   int      retval;

   mutex_lock(&zget_lock);
   retval = param + incr;
   param = retval;
   mutex_unlock(&zget_lock);
   return retval;
}


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

//  Start a detached thread using a simplified protocol.
//  Will not make a zombie if caller exits without checking thread status.

pthread_t start_detached_thread(void * threadfunc(void *), void * arg)
{
   pthread_attr_t pthattr;
   pthread_t      pthtid;
   int            ii, err;

   pthread_attr_init(&pthattr);
   pthread_attr_setdetachstate(&pthattr,PTHREAD_CREATE_DETACHED);

   for (ii = 0; ii < 1000; ii++)
   {
      err = pthread_create(&pthtid,&pthattr,threadfunc,arg);
      if (! err) return pthtid;
      zsleep(0.001);
      if (err == EAGAIN) continue;                                               //  this shit happens
      break;
   }

   zexit(1,"pthread_create() failure: %s",strerror(err));
   return 0;                                                                     //  avoid compiler warning
}


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

//  Start a thread using a simplified protocol.
//  Caller must call wait_Jthread() to avoid creating a zombie process.

pthread_t start_Jthread(void * threadfunc(void *), void * arg)
{
   pthread_t   tid;
   int         err;

   err = pthread_create(&tid, null, threadfunc, arg);                            //  retry EAGAIN failure removed          24.60
   if (! err) return tid;                                                        //  (does not work)
   zexit(1,"pthread_create() failure: %s",strerror(err));                        //  fail totally
   return 0;
}


//  wait for thread to exit.

int wait_Jthread(pthread_t tid)
{
   int      err;

   err = pthread_join(tid, null);
   if (! err) return 0;
   zexit(1,"pthread_join() failure: %s",strerror(err));
   return 0;
}


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

//  Synchronize execution of multiple threads.
//  Simultaneously resume NT calling threads.
//  from main():        synch_threads(NT)    /* setup to synch NT threads */
//  from each thread:   synch_threads(0)     /* suspend, resume simultaneously */
//
//  Each calling thread will suspend execution until all threads have suspended,
//  then they will all resume execution at the same time. If NT is greater than
//  the number of calling threads, the threads will never resume.

void synch_threads(int NT)
{
   static pthread_barrier_t   barrier;
   static int                 bflag = 0;

   if (NT) {                                                                     //  main(), initialize
      if (bflag) pthread_barrier_destroy(&barrier);
      pthread_barrier_init(&barrier,null,NT);
      bflag = 1;
      return;
   }

   pthread_barrier_wait(&barrier);                                               //  thread(), wait for NT threads
   return;                                                                       //  unblock
}


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

//  Test if caller is from the main() thread or from a created thread.
//  return 1 if main(), else 0

int main_thread()
{
   if (pthread_equal(pthread_self(),zfuncs::tid_main)) return 1;
   return 0;
}


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

//  set a CPU affinity for the calling process or thread
//  cpu is in the range 0 to (processor core count) - 1

void set_cpu_affinity(int cpu)
{
   int         err;
   static int  ftf = 1, Nsmp;
   cpu_set_t   cpuset;

   if (ftf) {                                                                    //  first call
      ftf = 0;
      Nsmp = get_nprocs();                                                       //  get SMP CPU count
   }

   if (cpu >= Nsmp) return;

   CPU_ZERO(&cpuset);
   CPU_SET(cpu,&cpuset);
   err = sched_setaffinity(0,sizeof(cpuset),&cpuset);
   if (err) Plog(2,"set_cpu_affinity() %s \n",strerror(errno));
   return;
}


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

   int err = zshell(ch *options, ch *command, ...)

   Format and perform a shell command, wait for completion, return status.

   options: may be null or may contain any of the following substrings:
             "log"    write command to log file, stdout
             "ack"    popup user ACK message if the shell command has an error
             "noerr"  do not log error status

   command:  shell command with optional '%' printf formats
     ...  :  optional arguments to stuff into printf formats

   returns: status of the shell command

***/


int zshell(ch *options, ch *command, ...)
{
   int         Flog, Fack, Fnoerr;
   va_list     arglist;
   int         err, cc, ccmax = 2*XFCC;
   ch          command2[2*XFCC];

   Flog = Fack = Fnoerr = 0;

   if (options) {
      if (strstr(options,"log")) Flog = 1;                                       //  set options
      if (strstr(options,"ack")) Fack = 1;
      if (strstr(options,"noerr")) Fnoerr = 1;
   }

   va_start(arglist,command);                                                    //  format command
   cc = vsnprintf(command2,ccmax,command,arglist);
   va_end(arglist);
   if (cc >= ccmax) zappcrash("zshell: buffer overflow: %d",cc);

   if (Flog) Plog(0,"zshell: %s \n",command2);                                   //  command > log file if wanted

   err = system(command2);                                                       //  run command, returns when done
   err = WEXITSTATUS(err);                                                       //  get command status

   if (err && ! Fnoerr) {                                                        //  suppress log of command and error     24.20
      if (! Flog) Plog(0,"zshell: %s \n",command2);                              //  log command if not already
      Plog(0,"zshell error: %s \n",strerror(err));                               //  log error
      if (Fack) zmessageACK(mainwin,"command: %s \n error: %s",
                                       command2, strerror(err));                 //  popup error to user if wanted
   }

   return err;                                                                   //  return completion status
}


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

//  Signal a running subprocess by name (name of executable or shell command).
//  Signal is "pause", "resume" or "kill". If process is paused, kill may not work,
//  so issue resume first if process is paused.

int signalProc(ch *pname, ch *signal)
{
   pid_t       pid;
   FILE        *fid;
   ch          buff[100], *pp;
   int         err, nsignal = 0;

   snprintf(buff,100,"ps -C %s h o pid",pname);
   fid = popen(buff,"r");                                                        //  popen() instead of system()
   if (! fid) return 2;
   pp = fgets(buff,100,fid);
   pclose(fid);
   if (! pp) return 4;

   pid = atoi(buff);
   if (! pid) return 5;

   if (strmatch(signal,"pause")) nsignal = SIGSTOP;
   if (strmatch(signal,"resume")) nsignal = SIGCONT;
   if (strmatch(signal,"kill")) nsignal = SIGKILL;

   err = kill(pid,nsignal);
   return err;
}


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

//  fgets() with additional feature: trailing \n \r are removed.
//  optional bf flag: true if trailing blanks are to be removed.
//  trailing null character is assured.

ch * fgets_trim(ch *buff, int maxcc, FILE *fid, int bf)
{
   int      cc;
   ch       *pp;

   pp = fgets(buff,maxcc,fid);
   if (! pp) return pp;
   cc = strlen(buff);
   if (bf) while (cc && buff[cc-1] > 0 && buff[cc-1] <= ' ') --cc;
   else    while (cc && buff[cc-1] > 0 && buff[cc-1] < ' ') --cc;
   buff[cc] = 0;
   return pp;
}


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

//  Return 1 if both filespecs have the same folder, else return 0.
//  Both folders must be specified, at least one with ending '/'
//  (true if a file name is present)

int samefolder(ch *file1, ch *file2)
{
   ch       *p1, *p2;
   int      cc1, cc2, cc;

   p1 = strrchr(file1,'/');                                                      //  /dir1/dir2
   p2 = strrchr(file2,'/');                                                      //  /dir1/dir2/file
   cc1 = cc2 = 0;
   if (p1) cc1 = p1 - file1;                                                     //  /dir1/dir2/file
   if (p2) cc2 = p2 - file2;                                                     //  |         |
   if (cc2 > cc1) cc = cc2;                                                      //  0         cc
   else cc = cc1;
   if (cc == 0) return 0;
   if (strmatchN(file1,file2,cc)) return 1;
   return 0;
}


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

   Parse a pathname (filespec) and return its components.
   Returned strings are allocated in static memory (no zfree needed).
   Next call replaces the data in the static strings.
   Limits: folder: 1000  file: 200  ext: 8
   Missing components are returned as null pointers.

   input ppath         outputs

   /name1/name2/       folder /name1/name2/ with no file
   /name1/name2        folder /name1/name2/ if name2 a folder,
                       otherwise folder /name1/ and file name2
   /name1/name2.xxx    if .xxx < 8 chars, returns file name2 and ext .xxx,
                       otherwise returns file name2.xxx and no ext

   returns 0 if no error, else 1

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

int parsefile(ch *ppath, ch **pfolder, ch **pfile, ch **pext)
{
   STATB          statB;
   static ch      folder[1000], file[200], ext[8];
   ch             *pp;
   int            err, cc1, cc2;

   *pfolder = *pfile = *pext = null;

   cc1 = strlen(ppath);
   if (cc1 > 999) return 1;                                                      //  ppath too long

   strcpy(folder,ppath);
   *pfolder = folder;

   err = stat(folder,&statB);                                                    //  have folder only
   if (! err && S_ISDIR(statB.st_mode)) return 0;

   pp = (ch *) strrchr(folder,'/');
   if (! pp) return 1;                                                           //  illegal

   pp++;
   cc2 = pp - folder;
   if (cc2 < 2 || cc2 == cc1) return 0;                                          //  have /xxxx  or  /xxxx/

   if (strlen(pp) > 199) return 1;                                               //  filename too long

   strcpy(file,pp);                                                              //  file part
   *pfile = file;
   *pp = 0;                                                                      //  remove from folder part

   pp = (ch *) strrchr(file,'.');
   if (! pp || strlen(pp) > 7) return 0;                                         //  file part, no .ext

   strcpy(ext,pp);                                                               //  .ext part
   *pext = ext;
   *pp = 0;                                                                      //  remove from file part
   return 0;
}


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

//  Move a source file to a destination file and delete the source file.
//  Equivalent to rename(), but the two files MAY be on different file systems.
//  Pathnames must be absolute (start with '/').
//  Returns 0 if OK, +N if not.

int renamez(ch *file1, ch *file2)
{
   ch       *pp1, *pp2;
   int      err, Frename = 0;

   if (*file1 != '/' || *file2 != '/') return 1;                                 //  not absolute pathnames

   pp1 = strchr((ch *) file1+1,'/');
   pp2 = strchr((ch *) file2+1,'/');
   if (! pp1 || ! pp2) return 2;

   *pp1 = *pp2 = 0;
   if (strmatch(file1,file2)) Frename = 1;
   *pp1 = *pp2 = '/';

   if (Frename) {                                                                //  same top folder
      err = rename(file1,file2);
      if (err) return errno;
      return 0;
   }

   pp1 = zescape_quotes(file1);
   pp2 = zescape_quotes(file2);
   err = zshell(0,"mv -f \"%s\" \"%s\" ",pp1,pp2);
   zfree(pp1);
   zfree(pp2);
   return err;
}


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

//  Check if a folder exists. If not, ask user if it should be created.
//  Returns 0 if OK or +N if error or user refused to create.
//  The user is notified of failure, no other message needed.
//  path may not have embedded quotes.

int check_create_dir(ch *path)
{
   int      err, yn;
   STATB    statB;

   err = stat(path,&statB);                                                      //  check status
   if (! err) {
      if (S_ISDIR(statB.st_mode)) return 0;                                      //  exists, folder, OK
      else {
         zmessageACK(mainwin,"%s \n %s",path,strerror(ENOTDIR));                 //  exists, not a folder
         return ENOTDIR;
      }
   }

   if (errno != ENOENT) {
      zmessageACK(mainwin,"%s \n %s",path,strerror(errno));                      //  error other than missing
      return errno;
   }

   yn = zmessageYN(0,"create folder? \n %s",path);                               //  ask to create
   if (! yn) return ENOENT;

   err = zshell("ack","mkdir -p -m 0750 \"%s\" ",path);                          //  create
   if (! err) return 0;

   zmessageACK(mainwin,"%s \n %s",path,strerror(errno));                         //  failed to create
   return errno;
}


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

//  copy a file using shell 'cp' command
//  file owner, permissions, and timestamps are copied
//  returns 0 if OK, else errno

int cp_copy(ch *sfile, ch *dfile)
{
   ch    *pps, *ppd;

   if (strmatch(sfile,dfile)) {
      Plog(0,"ignore copy file to self: %s \n",sfile);
      return 0;
   }

   pps = zescape_quotes(sfile);
   ppd = zescape_quotes(dfile);

   int err = zshell(0,"cp -f -p  \"%s\" \"%s\" ",pps,ppd);

   zfree(pps);
   zfree(ppd);

   return err;
}


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

//  get the available space on disk of the given file
//  returns disk space in MB (limit 4 billion MB)

uint diskspace(ch *file)
{
   ch       command[200], buff[200];
   ch       *pp;
   uint     avail;
   FILE     *fid;

   pp = zescape_quotes(file);
   snprintf(command,200,"df --output=avail \"%s\" ",pp);
   zfree(pp);

   fid = popen(command,"r");
   if (! fid) return 0;
   pp = fgets(buff,200,fid);                                                     //  "Avail" header
   pp = fgets(buff,200,fid);                                                     //  decimal number, KB space
   pclose(fid);
   if (! pp) return 0;
   avail = 0.001 * atoll(pp);                                                    //  MB space
   return avail;
}


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

//  if a file has an incorrect .ext, return the correct .ext
//  return null if file is OK or cannot be determined
//  returned .ext is in a static buffer

ch * get_file_extension(ch *file)
{
   ch       *fext1;
   ch       *extlist, *fext2, *pp;
   ch       *buff;
   int      cc;
   FILE     *fid;

   static ch fext3[20];

   errno = 0;
   cc = strlen(file) + 20;
   buff = (ch *) zmalloc(cc,0);
   pp = zescape_quotes(file);
   snprintf(buff,cc,"file --extension %s",pp);                                   //  'file' command - get correct extensions
   zfree(pp);
   fid = popen(buff,"r");
   if (! fid) goto ret0;
   extlist = fgets(buff,cc,fid);                                                 //  /.../filename.ext: ext1/ext2/...
   pclose(fid);
   if (! extlist) goto ret0;
   extlist = strrchr(extlist,':');                                               //  extlist = : ext1/ext2/...
   if (! extlist) goto ret0;
   extlist += 2;                                                                 //  extlist = ext1/ext2/...

   fext1 = strrchr(file,'.');                                                    //  fext1 = file current .ext
   if (! fext1) fext1 = ".xxx";
   if (strcasestr(extlist,fext1+1)) goto ret0;                                   //  fext1 found in extlist

   fext2 = extlist;
   pp = strchr(fext2,'/');                                                       //  fext2 = first in extlist
   if (pp) *pp = 0;

   strncpy0(fext3,fext2,20);                                                     //  return correct .ext in static buffer
   zfree(buff);
   return fext3;

ret0:
   if (errno) Plog(0,"%s\n",strerror(errno));
   zfree(buff);
   return 0;
}


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

//  Return all the file names in a folder, sorted in alphabetic order.
//  Subfolders are not included.
//  The 'files' argument is allocated and filled with pointers to file names.
//  (the names in the folder, not the full path names)
//  The number of files found is returned.
//  -1 is returned if the folder is invalid or other error.
//  If 'files' is returned non-zero, it is subject to zfree()

int zreaddir(ch *folder, ch **&files)
{
   struct dirent  *dirent1;

   int      Nfiles = 0, maxfiles = 100;
   DIR      *direc;
   ch       **ufiles, **ufiles2;

   files = 0;                                                                    //  nothing returned yet

   ufiles = (ch **) zmalloc(maxfiles * sizeof(ch *),"zreaddir");                 //  starting space

   direc = opendir(folder);                                                      //  open caller's folder
   if (! direc) return -1;

   while (true)
   {
      if (Nfiles == maxfiles)                                                    //  out of space
      {
         ufiles2 = (ch **) zmalloc(2 * maxfiles * sizeof(ch *),"zreaddir");      //  allocate new space = 2x old space
         memcpy(ufiles2,ufiles, maxfiles * sizeof(ch *));                        //  copy data to new space
         zfree(ufiles);                                                          //  free old space
         ufiles = ufiles2;                                                       //  set new space
         maxfiles *= 2;                                                          //  new capacity
      }

      dirent1 = readdir(direc);                                                  //  get next file in folder
      if (! dirent1) break;
      if (dirent1->d_type != DT_REG) continue;                                   //  skip subfolders
      ufiles[Nfiles] = zstrdup(dirent1->d_name,"zreaddir");                      //  add to file list
      Nfiles++;
      continue;
   }

   closedir(direc);

   if (Nfiles > 1) HeapSort(ufiles,Nfiles);                                      //  sort file list

   files = ufiles;                                                               //  return allocated file list
   return Nfiles;                                                                //  return file count
}


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

//  int NR = zreadfile(ch *filename, ch &**rrecs)
//
//  Read a text file into a list of ch * strings, 1 record per string.
//  The strings are allocated as needed. The number of records is returned.
//  Returned: -1  error (errno is set)
//             0  empty file
//            NR  records read, > 0
//  Returned record N: rrecs[N]  (ch *)
//  Trailing blanks and '\n' characters are removed.
//  The maximum record length is 1000 chars, including terminating null.
//  The maximum record count is 1000 records.
//  Null records ("" or "\n") are not included in output.
//  rrecs[NR] (last + 1) is a null pointer.

int zreadfile(ch *filename, ch **&rrecs)
{
   FILE           *fid;
   ch             *recs[1001];
   ch             buff[1001], *pp;
   int            cc, NR = 0;

   rrecs = 0;                                                                    //  initz. no data

   fid = fopen(filename,"r");                                                    //  open file
   if (! fid) return -1;

   while (true)
   {
      pp = fgets(buff,1001,fid);                                                 //  read record
      if (! pp) break;                                                           //  EOF
      cc = strlen(pp);
      if (cc > 999) {
         zmessageACK(mainwin,"zreadfile() record too long %s",filename);
         errno = EFBIG;
         return -1;
      }

      while (cc && pp[cc-1] > 0 && pp[cc-1] <= ' ') --cc;                        //  remove trailing \n, \r, blanks, etc.
      pp[cc] = 0;                                                                //  terminating null
      if (cc == 0) continue;                                                     //  discard null recs

      recs[NR] = (ch *) zmalloc(cc+1,"zreadfile");                               //  allocate memory
      memcpy(recs[NR],pp,cc+1);                                                  //  copy record
      NR++;
      if (NR == 1000) {
         zmessageACK(mainwin,"zreadfile() too many records %s",filename);
         errno = EFBIG;
         return -1;
      }
   }

   fclose(fid);
   recs[NR] = 0;                                                                 //  last record + 1 = null

   cc = (NR + 1) * sizeof(ch *);                                                 //  allocate caller rrecs list
   rrecs = (ch **) zmalloc(cc,"zreadfile");
   memcpy(rrecs,recs,cc);                                                        //  copy record pointers + null

   return NR;
}


//  int NR = zwritefile(ch *filename, ch **rrecs)
//  write array of records to a file, each with trailing \n character.
//  EOF is signalled with a null pointer: rrecs[last] = null
//  returns no. records written (>= 0) or -1 if file error.

int zwritefile(ch *filename, ch **rrecs)
{
   FILE           *fid;
   int            nr, nn;

   fid = fopen(filename,"w");                                                    //  open file
   if (! fid) return -1;

   for (nr = 0; nr < 1000; nr++)
   {
      if (! rrecs[nr]) break;
      nn = fprintf(fid,"%s\n",rrecs[nr]);
      if (nn <= 0) break;
   }

   fclose(fid);
   return nr;
}


//  free allocated records and their pointer list

void zreadfile_free(ch **&rrecs)
{
   for (int ii = 0; rrecs[ii]; ii++)                                             //  loop until null pointer
      zfree(rrecs[ii]);
   zfree(rrecs);
   rrecs = 0;                                                                    //  set no data
   return;
}


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

   utility to measure CPU time spent in various functions or code blocks

   cpu_profile_init()            initialize at start of test
   cpu_profile_enter(fnum)       at entry to a function
   cpu_profile_exit(fnum)        at exit from a function
   cpu_profile_report()          report CPU time per function

   Methodology: cpu_profile_init() starts a thread that suspends and runs every
   1 millisecond and updates a timer.
   cpu_profile_enter() and cpu_profile_exit() accumulate the time difference between
   entry and exit of code being measured. This may be zero because of the long interval
   between timer updates. Accuracy comes from statistical sampling over many seconds,
   so that if the time spent in a monitored function is significant, it will be accounted
   for. The accuracy is better than 1% as long as the measured function or code block
   consumes a second or more of CPU time during the measurement period.
   The "fnum" argument (1-99) designates the function or code block being measured.
   cpu_profile_report() stops the timer thread and reports time consumed per function,
   using the "fnum" tags in the report.
   The functions cpu_profile_enter() and cpu_profile_exit() subtract the timer
   difference and add to a counter per fnum, so the added overhead is insignificant.
   They are inline functions defined as follows:
   enter:  cpu_profile_timer = cpu_profile_elapsed;
   exit:   cpu_profile_table[fnum] += cpu_profile_elapsed - cpu_profile_timer;

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

VOL double   cpu_profile_table[100];
VOL double   cpu_profile_timer;
VOL double   cpu_profile_elapsed;
VOL int      cpu_profile_kill = 0;

void cpu_profile_init()
{
   void *   cpu_profile_timekeeper(void *);

   for (int ii = 0; ii < 99; ii++)
      cpu_profile_table[ii] = 0;
   cpu_profile_elapsed = 0;
   start_detached_thread(cpu_profile_timekeeper,null);
}

void cpu_profile_report()
{
   cpu_profile_kill++;

   Plog(1,"elapsed: %.2f \n",cpu_profile_elapsed);

   for (int ii = 0; ii < 100; ii++)
   {
      double dtime = cpu_profile_table[ii];
      if (dtime) Plog(1,"cpu profile func: %d  time: %.2f \n",ii,dtime);
   }
}

void * cpu_profile_timekeeper(void *)
{
   timeval  time0, time1;

   gettimeofday(&time0,0);

   while (true)
   {
      gettimeofday(&time1,0);
      cpu_profile_elapsed = time1.tv_sec - time0.tv_sec
              + 0.000001 * (time1.tv_usec - time0.tv_usec);
      zsleep(0.001);
      if (cpu_profile_kill) break;
   }

   cpu_profile_kill = 0;
   return 0;
}


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

//  Returns hard page fault rate in faults/second.
//  First call starts a thread that runs every 2 seconds and keeps a
//  weighted average of hard fault rate for the last few intervals.
//  This is a means to detect if a process is thrashing for lack of memory.

namespace pagefaultrate_names {
   int      ftf = 1;
   int      samples = 0;
   int      faultrate = 0;
   double   time1, time2;
   void * threadfunc(void *);
}

int pagefaultrate()
{
   using namespace pagefaultrate_names;

   if (ftf) {
      ftf = 0;
      start_detached_thread(threadfunc,0);
      time1 = get_seconds();
   }

   return faultrate;
}

void * pagefaultrate_names::threadfunc(void *)
{
   using namespace pagefaultrate_names;

   FILE        *fid;
   ch          *pp, buff[200];
   double      pfs1, pfs2, fps, elaps;

   while (true)
   {
      sleep(2);

      time2 = get_seconds();
      elaps = time2 - time1;
      time1 = time2;

      fid = fopen("/proc/self/stat","r");
      if (! fid) break;
      pp = fgets(buff,200,fid);
      fclose(fid);
      if (! pp) break;
      pp = strchr(pp,')');                                                       //  closing ')' after (short) filename
      if (pp) parseprocrec(pp+1,10,&pfs1,11,&pfs2,null);
      fps = (pfs1 + pfs2) / elaps;
      faultrate = 0.7 * faultrate + 0.3 * fps;
   }

   Plog(0,"pagefaultrate() failure \n");
   return 0;
}


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

    substringR()

    ch * substringR(ch *string, ch *delims, int Nth)

    Get the Nth substring in an input string, which contains at least N
    substrings delimited by the character(s) in delim (e.g. blank, comma).
    Nth >= 1.

    Returns a pointer to the found substring (actually a pointer to a
    copy of the found substring, with a null terminator appended).
    The returned pointer is a subject for zfree().

    If a delimiter is immediately followed by another delimiter, it is
    considered a substring with zero length, and the string "" is returned.

    Leading blanks in a substring are omitted from the returned substring.
    A substring with only blanks is returned as "".

    The last substring may be terminated by null or a delimiter.

    Characters within quotes (") are treated as data within a substring,
    i.e. blanks and delimiters are not processed as such.
    The quotes are removed from the returned substring.

    If there are less than Nth substrings, a null pointer is returned.

    This function is thread-safe.
    See below for simpler non-thread-safe version.

    Example: input string: ,a,bb,  cc,   ,dd"ee,ff"ggg,
             (first and last characters are comma)
             delimiter: comma
             Nth   returned string
              1:   (null)
              2:   a
              3:   bb
              4:   cc
              5:   (one blank)
              6:   ddee,ffggg
              7:   (null)        last+1 substring

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

ch * substringR(ch *string, ch *delims, int Nth)
{
   ch       *pf1, pf2[2000];                                                     //  2000 char. limit
   ch       quote = '"';
   int      nf, fcc = 0;

   if (! string || ! *string) return 0;                                          //  bad call
   if (Nth < 1) return 0;

   pf1 = (ch *) string - 1;                                                      //  start parse
   nf = 0;

   while (nf < Nth)
   {
      pf1++;                                                                     //  start substring
      nf++;
      fcc = 0;

      while (*pf1 == ' ') pf1++;                                                 //  skip leading blanks

      while (true)
      {
         if (*pf1 == quote) {                                                    //  pass chars between quotes
            pf1++;                                                               //  (but without the quotes)
            while (*pf1 && *pf1 != quote) pf2[fcc++] = *pf1++;
            if (*pf1 == quote) pf1++;
         }
         else if (strchr(delims,*pf1) || *pf1 == 0) break;                       //  found delimiter or null
         else pf2[fcc++] = *pf1++;                                               //  pass normal character
         if (fcc > 1999) zappcrash("substringR() too long");
      }

      if (*pf1 == 0) break;                                                      //  end of input string
   }

   if (nf < Nth) return 0;                                                       //  no Nth substring
   if (fcc == 0 && *pf1 == 0) return 0;                                          //  empty substring

   pf2[fcc] = 0;
   return zstrdup(pf2,"substringR");                                             //  returned string (needs zfree())
}


//  alternative with one delimiter

ch * substringR(ch *string, ch delim, int Nth)
{
   ch     delims[2] = "x";
   *delims = delim;
   return substringR(string,delims,Nth);
}


//  non-thread-safe versions without zfree() requirement
//  returned substring is in static memory
//  only the last 1000 results are kept       <----- NOTE limitation

ch * substring(ch *string, ch *delims, int Nth)                                  //  24.40
{
   ch           *s1;
   static ch    *s2[1000];
   static int   kk = -1;
   
   if (kk == -1) memset(s2,0,1000*sizeof(ch *)); 
   
   s1 = substringR(string,delims,Nth);
   if (! s1) return 0;
   
   kk++;
   if (kk == 1000) kk = 0;
   if (s2[kk]) zfree(s2[kk]);
   s2[kk] = s1;
   return s1;
}


ch * substring(ch *string, ch delim, int Nth)
{
   ch     delims[2] = "x";
   *delims = delim;
   return substring(string,delims,Nth);
}


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

//  Produce random value from hashed input string.
//  Output range is 0 to max-1.
//  Benchmark: 0.2 usec for 99 char. string, 3 GHz Core i5

int strHash(ch *string, uint max)
{
   uint     hash = 1357;
   uch      byte;

   while ((byte = *string++))
   {
      hash = hash * (byte + 111);
      hash = hash ^ (hash >> 9);
      hash = hash ^ (byte << 9);
   }

   hash = hash % max;
   return hash;
}


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

//  Copy string with specified max. length (including null terminator).
//  truncate if needed. null terminator is always supplied.
//  Returns 0 if no truncation, 1 if input string was truncated to fit.

int strncpy0(ch *dest, ch *source, uint cc)
{
   strncpy(dest,source,cc);
   dest[cc-1] = 0;
   if (strlen(source) >= cc) return 1;                                           //  truncated
   else return 0;
}


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

//  Copy string with blank pad to specified length.  No null is added.

void strnPad(ch *dest, ch *source, int cc)
{
   strncpy(dest,source,cc);
   int ii = strlen(source);
   for (int jj = ii; jj < cc; jj++) dest[jj] = ' ';
}


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

//  Remove trailing blanks from a string. Returns remaining length.

int strTrim(ch *dest, ch *source)
{
   if (dest != source) strcpy(dest,source);
   return strTrim(dest);
}

int strTrim(ch *dest)
{
   int  ii = strlen(dest);
   while (ii && (dest[ii-1] == ' ')) dest[--ii] = 0;
   return ii;
}


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

//  Remove leading and trailing blanks from a string.
//  Returns remaining length, possibly zero.

int strTrim2(ch *dest, ch *source)
{
   ch         *pp1, *pp2;
   int         cc;

   pp1 = source;
   pp2 = source + strlen(source) - 1;
   while (*pp1 == ' ') pp1++;
   if (*pp1 == 0) {
      strcpy(dest,"");                                                           //  null or blank input
      return 0;
   }
   while (*pp2 == ' ' && pp2 > pp1) pp2--;
   cc = pp2 - pp1 + 1;
   memmove(dest,pp1,cc);
   dest[cc] = 0;
   return cc;
}

int strTrim2(ch *string)
{
   return strTrim2(string,string);
}


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

//  Remove all blanks from a string. Returns remaining length.

int strCompress(ch *dest, ch *source)
{
   if (dest != source) strcpy(dest,source);
   return strCompress(dest);
}

int strCompress(ch *string)
{
   int   ii, jj;

   for (ii = jj = 0; string[ii]; ii++)
   {
      if (string[ii] != ' ')
      {
         string[jj] = string[ii];
         jj++;
      }
   }
   string[jj] = 0;
   return jj;
}


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

//  Concatenate multiple strings, staying within a specified overall length.
//  The destination string is also the first source string.
//  Null marks the end of the source strings (omission --> crash).
//  Output is truncated to fit within the specified length.
//  A final null is assured and is included in the length.
//  Returns 0 if OK, 1 if truncation was needed.

int strncatv(ch *dest, int maxcc, ch *source, ...)
{
   ch         *ps;
   va_list     arglist;

   maxcc = maxcc - strlen(dest) - 1;
   if (maxcc < 0) return 1;
   va_start(arglist,source);
   ps = source;

   while (ps)
   {
      strncat(dest,ps,maxcc);
      maxcc = maxcc - strlen(ps);
      if (maxcc < 0) break;
      ps = va_arg(arglist,ch *);
      if (! ps || ps == (ch *) 0x100000000) break;                               //  ARM bug
   }

   va_end(arglist);
   if (maxcc < 0) return 1;
   return 0;
}


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

//  Match 1st string to N additional strings.
//  Return matching string number 1 to N or 0 if no match.
//  Supply a null argument for end of list.

int strmatchV(ch *string, ...)
{
   int         match = 0;
   ch          *stringN;
   va_list     arglist;

   va_start(arglist,string);

   while (true)
   {
      stringN = va_arg(arglist, ch *);
      if (stringN == null || stringN == (ch *) 0x100000000)                      //  ARM bug
      {
         va_end(arglist);
         return 0;
      }

      match++;
      if (strmatch(string,stringN))
      {
         va_end(arglist);
         return match;
      }
   }
}


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

//  convert string to upper case

void strToUpper(ch *string)
{
   int   ii;
   ch    jj;
   int   delta = 'A' - 'a';

   for (ii = 0; (jj = string[ii]); ii++)
        if ((jj >= 'a') && (jj <= 'z')) string[ii] += delta;
}

void strToUpper(ch *dest, ch *source)
{
   strcpy(dest,source);
   strToUpper(dest);
}


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

//  convert string to lower case

void strToLower(ch *string)
{
   int   ii;
   ch    jj;
   int   delta = 'a' - 'A';

   for (ii = 0; (jj = string[ii]); ii++)
        if ((jj >= 'A') && (jj <= 'Z')) string[ii] += delta;
}

void strToLower(ch *dest, ch *source)
{
   strcpy(dest,source);
   strToLower(dest);
}


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

//  Copy string strin to strout, replacing every occurrence
//  of the substring ssin with the substring ssout.
//  maxcc is the limit for strout. The actual cc is returned.
//  Replacement strings may be longer or shorter or have zero length.

int repl_1str(ch *strin, ch *strout, int maxcc, ch *ssin, ch *ssout)
{
   int     cc, cc1, cc2, ccout, nfound;
   ch      *pp, *pp1, *pp2;

   pp1 = strin;
   pp2 = strout;
   cc1 = strlen(ssin);
   cc2 = strlen(ssout);
   nfound = 0;
   ccout = 0;

   while ((pp = strstr(pp1,ssin)))
   {
      nfound++;
      cc = pp - pp1;
      if (ccout + cc >= maxcc) goto stop;
      memcpy(pp2,pp1,cc);
      pp2 += cc;
      pp1 += cc;
      ccout += cc;
      if (ccout + cc2 >= maxcc) goto stop;
      memcpy(pp2,ssout,cc2);
      pp1 += cc1;
      pp2 += cc2;
      ccout += cc2;
   }

   cc = strlen(pp1);
   if (ccout + cc >= maxcc) goto stop;
   memcpy(pp2,pp1,cc);
   ccout += cc;

   stop:
   strout[ccout] = 0;

   return ccout;
}


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

//  Copy string strin to strout, replacing multiple substrings with replacement strings.
//  Multiple pairs of string arguments follow maxcc, a substring and a replacement string.
//  Last pair of string arguments must be followed by a null argument.
//  maxcc is the limit for strout. The actual cc is returned.
//  Replacement strings may be longer or shorter or have zero length.

int repl_Nstrs(ch *strin, ch *strout, int maxcc, ...)
{
   va_list     arglist;
   ch          *ssin, *ssout;
   ch          ftemp[2000];
   int         ftf, ccout;

   ftf = 1;
   ccout = 0;
   va_start(arglist,maxcc);

   while (true)
   {
      ssin = va_arg(arglist, ch *);
      if (! ssin || ssin == (ch *) 0x100000000) break;                           //  ARM bug
      ssout = va_arg(arglist, ch *);

      if (ftf) {
         ftf = 0;
         ccout = repl_1str(strin,strout,maxcc,ssin,ssout);
      }

      else {
         if (ccout >= 2000) goto stop;
         strcpy(ftemp,strout);
         ccout = repl_1str(ftemp,strout,maxcc,ssin,ssout);
      }
   }

   stop:
   va_end(arglist);
   return ccout;
}


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

//  Break up a long text string into lines no longer than cc2 chars.
//  If fake newlines ("\n") are found, replace them with real newlines.
//  Break unconditionally where newlines are found and remove them.
//  Break at last blank ch between cc1 and cc2 if present.
//  Break at last delimiter ch between cc1 and cc2 if present.
//  Break unconditionally at cc2 if none of the above.
//  Returns text lines in txout[*] with count as returned function value.
//  txout[*] are subjects for zfree().

int breakup_text(ch *txin0, ch **&txout, ch *delims, int cc1, int cc2)
{
   ch       *txin;
   uch      ch1;
   int      ccmax;
   int      p1, p2, cc3, Nout;
   int      Np, Bp, Sp;

   txin = zstrdup(txin0,"breakup_text");
   ccmax = strlen(txin);
   txout = (ch **) zmalloc(100 * sizeof(ch *),"breakup_text");                   //  100 line limit

   if (strstr(txin0,"\\n"))                                                      //  replace "\n" with real newline chars
      repl_1str(txin0,txin,ccmax,"\\n","\n");

   Nout = p1 = 0;

   while (true)
   {
      p2 = p1;                                                                   //  input line position
      cc3 = 0;                                                                   //  output line cc

      Np = Bp = Sp = 0;

      while (txin[p2])                                                           //  scan further up to cc2 chars
      {
         ch1 = txin[p2];
         if (ch1 == '\n') { Np = p2; break; }                                    //  break out if newline found
         if (cc3 >= cc1) {
            if (ch1 == ' ') Bp = p2;                                             //  remember last ' ' found after cc1 chars
            if (delims && strchr(delims,ch1)) Sp = p2;                           //  remember last delimiter found after cc1
         }
         if (ch1 < 0)                                                            //  UTF8 wide character
            while ((ch1 = txin[p2+1]) < 0xC0) p2++;
         p2++;
         cc3++;
         if (cc3 == cc2) break;
      }

      if (! cc3 && ! Np) break;                                                  //  nothing left
      if (Np) cc3 = Np - p1;                                                     //  newline found
      else {
         if (cc3 < cc2) Bp = Sp = 0;                                             //  line fits cc2 limit
         if (Bp) cc3 = Bp - p1 + 1;                                              //  break at previous ' '
         else if (Sp) cc3 = Sp - p1 + 1;                                         //  break at previous delimiter
         else cc3 = p2 - p1;
      }
      if (txin[p1] == ' ' && cc3) { p1++; cc3--; }                               //  remove leading blank
      if (cc3 > 0) {                                                             //  avoid blank line
         txout[Nout] = (ch *) zmalloc(cc3+1,"breakup_text");
         strncpy0(txout[Nout],txin+p1,cc3+1);
         if (++Nout == 100) break;
      }
      p2 = p1 + cc3;
      if (Np) p2++;
      p1 = p2;
   }

   zfree(txin);
   return Nout;
}


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

//  Copy and convert string to hex string.
//  Each input character 'A' >> 3 output characters "41 "

void strncpyx(ch *out, ch *in, int ccin)
{
   int      ii, jj, c1, c2;
   ch       cx[] = "0123456789ABCDEF";

   if (! ccin) ccin = strlen(in);

   for (ii = 0, jj = 0; ii < ccin; ii++, jj += 3)
   {
      c1 = (uch) in[ii] >> 4;
      c2 = in[ii] & 15;
      out[jj] = cx[c1];
      out[jj+1] = cx[c2];
      out[jj+2] = ' ';
   }
   out[jj] = 0;
   return;
}


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

//  Strip trailing zeros from ascii floating numbers
//    (e.g. 1.230000e+02  -->  1.23e+02)

void StripZeros(ch *pNum)
{
   int     ii, cc;
   int     pp, k1, k2;
   ch      work[20];

   cc = strlen(pNum);
   if (cc >= 20) return;

   for (ii = 0; ii < cc; ii++)
   {
      if (pNum[ii] == '.')
      {
         pp = ii;
         k1 = k2 = 0;
         for (++ii; ii < cc; ii++)
         {
            if (pNum[ii] == '0')
            {
               if (! k1) k1 = k2 = ii;
               else k2 = ii;
               continue;
            }

            if ((pNum[ii] >= '1') && (pNum[ii] <= '9'))
            {
               k1 = 0;
               continue;
            }

            break;
         }

         if (! k1) return;

         if (k1 == pp + 1) k1++;
         if (k2 < k1) return;
         strcpy(work,pNum);
         strcpy(work+k1,pNum+k2+1);
         strcpy(pNum,work);
         return;
      }
   }
}


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

//  test for blank/null string
//  Returns status depending on input string:
//    0 not a blank or null string
//    1 argument string is NULL
//    2 string has zero length (*string == 0)
//    3 string is all blanks

int blank_null(ch *string)
{
   if (! string) return 1;                                                       //  null string
   if (! *string) return 2;                                                      //  zero length string
   int cc = strlen(string);
   for (int ii = 0; ii < cc; ii++)
      if (string[ii] != ' ') return 0;                                           //  non-blank string
   return 3;                                                                     //  blank string
}


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

//  clean \x escape sequences and replace them with the escaped character
//    \n >> newline  \" >> doublequote  \\ >> backslash   etc.
//  see  $ man ascii  for the complete list

int clean_escapes(ch *string)
{
   ch       *pp1 = string, *pp2 = string, *pp;
   ch       char1;
   ch       escapes[] = "abtnvfr";
   int      count = 0;

   while (true)
   {
      char1 = *pp1++;

      if (char1 == 0) {
         *pp2 = 0;
         return count;
      }

      else if (char1 == '\\')  {
         char1 = *pp1++;
         pp = strchr(escapes,char1);
         if (pp) char1 = pp - escapes + 7;
         count++;
      }

      *pp2++ = char1;
   }
}


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

//  Compute the graphic character count for a UTF8 character string.
//  Depends on UTF8 rules:
//    - ascii characters are positive (0x00 to 0x7F)
//    - 1st ch of multich sequence is negative (0xC0 to 0xFD)
//    - subsequent multichars are in the range 0x80 to 0xBF

int utf8len(ch *utf8string)
{
   int      ii, cc;
   ch       xlimit = 0xC0;

   for (ii = cc = 0; utf8string[ii]; ii++)
   {
      if (utf8string[ii] < 0)                                                    //  multibyte character
         while (utf8string[ii+1] < xlimit) ii++;                                 //  skip extra bytes
      cc++;
   }

   return cc;
}


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

//  Extract a UTF8 substring with a specified count of graphic characters.
//    utf8in     input UTF8 string
//    utf8out    output UTF8 string, which must be long enough
//    pos        initial graphic character position to get (0 = first)
//    cc         max. count of graphic characters to get
//    returns    number of graphic characters extracted, <= cc
//  Output string is null terminated after last extracted character.

int utf8substring(ch *utf8out, ch *utf8in, int pos, int cc)
{
   int      ii, jj, kk, posx, ccx;
   ch       xlimit = 0xC0;

   for (ii = posx = 0; posx < pos && utf8in[ii]; ii++)
   {
      if (utf8in[ii] < 0)
         while (utf8in[ii+1] < xlimit) ii++;
      posx++;
   }

   jj = ii;

   for (ccx = 0; ccx < cc && utf8in[jj]; jj++)
   {
      if (utf8in[jj] < 0)
         while (utf8in[jj+1] < xlimit) jj++;
      ccx++;
   }

   kk = jj - ii;

   strncpy(utf8out,utf8in+ii,kk);
   utf8out[kk] = 0;

   return   ccx;
}


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

//  check a character string for valid utf8 encoding
//  returns:  0 = OK,  1 = bad string

int utf8_check(ch *string)
{
   ch       *pp;
   uch      ch1, ch2, nch;

   for (pp = string; *pp; pp++)
   {
      ch1 = *pp;
      if (ch1 < 0x7F) continue;
      if (ch1 > 0xBF && ch1 < 0xE0) nch = 1;
      else if (ch1 < 0xF0) nch = 2;
      else if (ch1 < 0xF8) nch = 3;
      else if (ch1 < 0xFC) nch = 4;
      else if (ch1 < 0xFE) nch = 5;
      else return 1;
      while (nch) {
         pp++;
         ch2 = *pp;
         if (ch2 < 0x80 || ch2 > 0xBF) return 1;
         nch--;
      }
   }

   return 0;
}


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

//  check a character string for valid utf8 encoding
//  invalid characters are replaced with '?' 
//  returns no. of characters replaced (0 if no errors found)

int utf8_clean(ch *string)                                                       //  24.60
{
   int      badbytes = 0;
   ch       *pp1, *pp2;
   uch      ch1, ch2, nch;

   for (pp1 = string; *pp1; pp1++)
   {
      ch1 = *pp1;
      if (ch1 < 0x7F) continue;                                                  //  ascii, single byte

      if (ch1 > 0xBF && ch1 < 0xE0) nch = 1;                                     //  extra bytes
      else if (ch1 < 0xF0) nch = 2;
      else if (ch1 < 0xF8) nch = 3;
      else if (ch1 < 0xFC) nch = 4;
      else if (ch1 < 0xFE) nch = 5;
      else goto fix1;                                                            //  >5 invalid

      pp2 = pp1;
      while (nch) {                                                              //  check extra bytes
         pp1++;
         ch2 = *pp1;
         if (ch2 < 0x80 || ch2 > 0xBF) goto fix2;                                //  invalid
         nch--;
      }
      continue;

   fix1:                                                                         //  replace bad byte with '?'
      *pp1 = '?';
      badbytes++;
      continue;

   fix2:
      pp1 = pp2;                                                                 //  back to initial byte
      *pp1 = '?';                                                                //  replace with '?'
      badbytes++;
      continue;
   }

   return badbytes;
}


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

//  Find the Nth graphic character position within a UTF8 string
//    utf8in      input UTF8 string
//    Nth         graphic character position, zero based
//  returns starting character (byte) position of Nth graphic character
//  returns -1 if Nth is beyond the string length

int utf8_position(ch *utf8in, int Nth)
{
   int      ii, posx;
   ch       xlimit = 0xC0;

   for (ii = posx = 0; posx < Nth && utf8in[ii]; ii++)
   {
      if (utf8in[ii] < 0)                                                        //  multi-byte character
         while (utf8in[ii+1] && utf8in[ii+1] < xlimit) ii++;                     //  traverse member bytes
      posx++;
   }

   if (utf8in[ii]) return ii;
   return -1;
}


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

//  err = zsed(file, string1, string2 ... null)
//
//  replace string1/3/5... with string2/4/6... in designated file
//  returns    N  lines changed
//            -1  file not found
//            -2  other error (with message)

int zsed(ch *infile ...)
{
   int         err, ftf, nn;
   FILE        *fid1, *fid2;
   ch          *outfile, *pp;
   ch          buffin[1000], buffout[1000], buffxx[1000];
   ch          *stringin, *stringout;
   va_list     arglist;

   fid1 = fopen(infile,"r");
   if (! fid1) return -1;

   outfile = zstrdup(infile,"zsed",8);
   strcat(outfile,"-temp");
   fid2 = fopen(outfile,"w");
   if (! fid2) {
      Plog(0,"%d \n",strerror(errno));
      zfree(outfile);
      return -2;
   }

   nn = 0;

   while (true)
   {
      pp = fgets(buffin,500,fid1);
      if (! pp) break;

      va_start(arglist,infile);

      ftf = 1;

      while (true)
      {
         stringin = va_arg(arglist, ch *);
         if (! stringin || stringin == (ch *) 0x100000000) break;                //  ARM bug
         stringout = va_arg(arglist, ch *);
         if (! stringout || stringout == (ch *) 0x100000000) break;

         if (ftf) {
            ftf = 0;
            nn += repl_1str(buffin,buffout,1000,stringin,stringout);
         }
         else {
            strcpy(buffxx,buffout);
            nn += repl_1str(buffxx,buffout,1000,stringin,stringout);
         }
      }

      va_end(arglist);

      fputs(buffout,fid2);
   }

   fclose(fid1);
   err = fclose(fid2);
   if (err) {
      Plog(0,"%s \n",strerror(errno));
      zfree(outfile);
      return -2;
   }

   rename(outfile,infile);

   zfree(outfile);
   return nn;
}


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

//  zstrstr() and zstrcasestr() work like strstr() and strcasestr()
//  but the needle string "" does NOT match any haystack string.

ch * zstrstr(ch *haystack, ch *needle)
{
   if (! needle || ! *needle) return 0;
   return strstr(haystack,needle);
}

ch * zstrcasestr(ch *haystack, ch *needle)
{
   if (! needle || ! *needle) return 0;
   return strcasestr(haystack,needle);
}


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

//  strcpy() with overlap allowed

ch * zstrcpy(ch *dest, ch *source)
{
   int cc = strlen(source);
   memmove(dest,source,cc);
   dest[cc] = 0;
   return dest;
}


//  strncpy() with overlap allowed

ch * zstrncpy(ch *dest, ch *source, int cc)
{
   memmove(dest,source,cc);
   return dest;
}


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

//  works like strcmp(), but compare is terminated by \n as well as null

int zstrcmp(ch *s1, ch *s2)
{
   ch       *p1, *p2;
   int      nn;

   p1 = (ch *) strchr(s1,'\n');
   p2 = (ch *) strchr(s2,'\n');
   if (p1) *p1 = 0;
   if (p2) *p2 = 0;
   nn = strcmp(s1,s2);
   if (p1) *p1 = '\n';
   if (p2) *p2 = '\n';
   return nn;
}


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

//  works like strcmp(), but using char *args instead of const char*

int  zstrcmp2(ch *s1, ch *s2)
{
   return strcmp((cch *) s1, (cch *) s2);
}


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

//  works like strcasecmp(), but using char *args instead of const char*

int  zstrcasecmp(ch *s1, ch *s2)
{
   return strcasecmp((cch *) s1, (cch *) s2);
}


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

//  escape quote marks (" and ') in a string, for use in shell commands
//  returned file is subject for zfree()

ch * zescape_quotes(ch *str1)
{
   ch     *str2 = 0;
   int    cc;

   if (strchr(str1,'"') == 0) {
      str2 = zstrdup(str1,"zescape_quotes");
      return str2;
   }

   cc = strlen(str1);
   str2 = (ch *) zmalloc(cc+40,"zescape_quotes");
   repl_Nstrs(str1,str2,cc+40,"\"","\\\"","\'","\\\'",0);
   return str2;
}


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

   Conversion Utilities

   convSI(string, inum, delim)                     string to int
   convSI(string, inum, low, high, delim)          string to int with range check

   convSD(string, dnum, delim)                     string to double
   convSD(string, dnum, low, high, delim)          string to double with range check

   convSF(string, fnum, delim)                     string to float
   convSF(string, fnum, low, high, delim)          string to float with range check

   convIS(inum, string, cc)                        int to string with returned cc

   convDS(fnum, digits, string, cc)                double to string with specified
                                                     digits of precision and returned cc

   string      input (ch *) or output (ch *)
   inum        input (int) or output (int &)
   dnum        input (double) or output (double &)
   delim       optional returned delimiter (null or ch **)
   low, high   input range check (int or double)
   cc          output string length (int &)
   digits      input digits of precision (int) to be used for output string

   NOTE: decimal point may be comma or period.
         1000's separators must NOT be present.

   convIS and convDS also return the length cc of the string output.
   convDS accepts same formats as atof. Decimal point can be comma or period.
   convDS will use whatever format (f/e) gives the shortest result.
   Outputs like "e03" or "e+03" will be shortened to "e3".

   function status returned:
       0    normal conversion, no invalid digits, blank/null termination
       1    successful conversion, but trailing non-numeric found
       2    conversion OK, but outside specified limits
       3    null or blank string, converted to zero       (obsolete, now status 4)
       4    conversion error, invalid data in string
   overlapping statuses have following precedence: 4 3 2 1 0

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

//  Convert string to integer

int convSI(ch *string, int &inum, ch **delim)                                    //  use glib function
{
   ch       *ddelim = 0;
   int      err;

   inum = strtol(string,&ddelim,10);                                             //  convert next characters
   if (delim) *delim = ddelim;
   if (ddelim == string) err = 4;                                                //  no valid digits
   else if (*ddelim == '\0') err = 0;                                            //  null delimiter
   else if (*ddelim == ' ') err = 0;                                             //  blank delimiter
   else err = 1;                                                                 //  other delimiter
   return err;
}


int convSI(ch *string, int &inum, int lolim, int hilim, ch **delim)
{
   int stat = convSI(string,inum,delim);

   if (stat > 2) return stat;                                                    //  invalid or null/blank
   if (inum < lolim) return 2;                                                   //  return 2 if out of limits
   if (inum > hilim) return 2;                                                   //  (has precedence over status 1)
   return stat;                                                                  //  limits OK, return 0 or 1
}


//  Convert string to double   ***  status 3 --> status 4  ***

int convSD(ch *string, double &dnum, ch **delim)                                 //  use glib function
{
   ch       *ddelim = 0;
   int      err;

   dnum = strtod(string,&ddelim);
   if (delim) *delim = ddelim;
   if (ddelim == string) err = 4;                                                //  no valid digits
   else if (*ddelim == '\0') err = 0;                                            //  OK, null delimiter
   else if (*ddelim == ' ') err = 0;                                             //  OK, blank delimiter
   else err = 1;                                                                 //  OK, other delimiter
   return err;
}


int convSD(ch *string, double &dnum, double lolim, double hilim, ch **delim)
{
   int stat = convSD(string,dnum,delim);

   if (stat > 2) return stat;                                                    //  invalid or null/blank
   if (dnum < lolim) return 2;                                                   //  return 2 if out of limits
   if (dnum > hilim) return 2;                                                   //  (has precedence over status 1)
   return stat;                                                                  //  limits OK, return 0 or 1
}


int convSF(ch *string, float &fnum, ch **delim)
{
   double   dnum;
   int      err;
   err = convSD(string,dnum,delim);
   fnum = dnum;
   return err;
}


int convSF(ch *string, float &fnum, float lolim, float hilim, ch **delim)
{
   double   dnum, dlolim = lolim, dhilim = hilim;
   int      err;
   err = convSD(string,dnum,dlolim,dhilim,delim);
   fnum = dnum;
   return err;
}


//  Convert int to string with returned length.
//  (will never exceed 12 characters)

int convIS(int inum, ch *string, int *cc)
{
   int   ccc;

   ccc = snprintf(string,12,"%d",inum);
   if (cc) *cc = ccc;
   return 0;
}


//  Convert double to string with specified digits of precision.
//  Shortest length format (f/e) will be used.
//  Output length is returned in optional argument cc.
//  (will never exceed 20 characters)

int convDS(double dnum, int digits, ch *string, int *cc)                         //  bugfix: use memmove not strcpy
{
   ch     *pstr;

   snprintf(string,20,"%.*g",digits,dnum);

   pstr = strstr(string,"e+");                                                   //  1.23e+12  >  1.23e12
   if (pstr) memmove(pstr+1,pstr+2,strlen(pstr+2)+1);

   pstr = strstr(string,"e0");                                                   //  1.23e02  >  1.23e2
   if (pstr) memmove(pstr+1,pstr+2,strlen(pstr+2)+1);

   pstr = strstr(string,"e0");
   if (pstr) memmove(pstr+1,pstr+2,strlen(pstr+2)+1);

   pstr = strstr(string,"e-0");                                                  //  1.23e-02  >  1.23e-2
   if (pstr) memmove(pstr+2,pstr+3,strlen(pstr+3)+1);

   pstr = strstr(string,"e-0");
   if (pstr) memmove(pstr+2,pstr+3,strlen(pstr+3)+1);

   if (cc) *cc = strlen(string);

   return 0;
}


//  convert string to double, accepting either '.' or ',' decimal points.
//  if there is an error, zero is returned.

double atofz(ch *string)
{
   ch  string2[20], *pp;

   strncpy(string2,string,20);
   string2[19] = 0;
   pp = strchr(string2,',');
   if (pp) *pp = '.';
   return atof(string2);
}


//  format a number as "123 B" or "12.3 KB" or "1.23 MB" etc.
//  prec is the desired digits of precision to output.
//  WARNING: only the last 100 conversions remain available in memory.
//  Example formats for 3 digits of precision:
//    123 B,  999 B,  1.23 KB,  98.7 KB,  456 KB,  2.34 MB,  45.6 GB,  1.23 GB

ch * formatKBMB(double fnum, int prec)
{
   #define Bkilo 1024
   #define Bmega (Bkilo*Bkilo)
   #define Bgiga (Bkilo*Bkilo*Bkilo)

   ch            *units;
   static ch     *output[100];
   static int    ftf = 1, ii;
   double        gnum;

   if (ftf) {                                                                    //  keep last 100 conversions
      ftf = 0;
      for (ii = 0; ii < 100; ii++)
         output[ii] = (ch *) zmalloc(20,"formatKBMB");
   }

   gnum = fabs(fnum);

   if (gnum > Bgiga) {
      fnum = fnum / Bgiga;
      units = "GB";
   }
   else if (gnum > Bmega) {
      fnum = fnum / Bmega;
      units = "MB";
   }
   else if (gnum > Bkilo) {
      fnum = fnum / Bkilo;
      units = "KB";
   }
   else units = "B ";

   gnum = fabs(fnum);
   if (prec == 2 && gnum >= 99.5) prec++;                                        //  avoid e+nn formats
   if (prec == 3 && gnum >= 999.5) prec++;
   if (prec == 4 && gnum >= 9999.5) prec++;
   if (prec == 5 && gnum >= 99999.5) prec++;
   if (prec == 6 && gnum >= 999999.5) prec++;

   if (++ii > 99) ii = 0;
   snprintf(output[ii],20,"%.*g %s",prec,fnum,units);
   return output[ii];
}


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

    Wildcard string match

    Match candidate string to wildcard string containing any number of
    '*' or '?' wildcard characters. '*' matches any number of characters,
    including zero characters. '?' matches any one character.
    Returns 0 if match, 1 if no match.                                           <<---- WATCH OUT !

    Benchmark: 0.032 usec.       wild = *asdf*qwer?yxc
               3.3 GHz Core i5   match = XXXasdfXXXXqwerXyxc

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

int MatchWild(ch *pWild, ch *pString)
{
   int   ii, star;

new_segment:

   star = 0;
   while (pWild[0] == '*')
   {
      star = 1;
      pWild++;
   }

test_match:

   for (ii = 0; pWild[ii] && (pWild[ii] != '*'); ii++)
   {
      if (pWild[ii] != pString[ii])
      {
         if (! pString[ii]) return 1;
         if (pWild[ii] == '?') continue;
         if (! star) return 1;
         pString++;
         goto test_match;
      }
   }

   if (pWild[ii] == '*')
   {
      pString += ii;
      pWild += ii;
      goto new_segment;
   }

   if (! pString[ii]) return 0;
   if (ii && pWild[ii-1] == '*') return 0;
   if (! star) return 1;
   pString++;
   goto test_match;
}


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

    Wildcard string match - ignoring case
    Works like MatchWild() above, but case is ignored.

***/

int MatchWildCase(ch *pWild, ch *pString)
{
   int   ii, star;

new_segment:

   star = 0;
   while (pWild[0] == '*')
   {
      star = 1;
      pWild++;
   }

test_match:

   for (ii = 0; pWild[ii] && (pWild[ii] != '*'); ii++)
   {
      if (! strmatchcaseN(pWild+ii,pString+ii,1))                                //  the only difference
      {
         if (! pString[ii]) return 1;
         if (pWild[ii] == '?') continue;
         if (! star) return 1;
         pString++;
         goto test_match;
      }
   }

   if (pWild[ii] == '*')
   {
      pString += ii;
      pWild += ii;
      goto new_segment;
   }

   if (! pString[ii]) return 0;
   if (ii && pWild[ii-1] == '*') return 0;
   if (! star) return 1;
   pString++;
   goto test_match;
}


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

   SearchWild  - wildcard file search

   Find all files with total /pathname/filename matching a pattern,
   which may have any number of the wildcard characters '*' and '?'
   in either or both the pathname and filename.

   ch * SearchWild(ch *wfilespec, int &flag)

   inputs:  flag = 1 to start a new search
            flag = 2 abort a running search
            *** do not modify flag within a search ***

            wfilespec = filespec to search with optional wildcards
               e.g. "/name1/na*me2/nam??e3/name4*.ext?"

   return:  a pointer to one matching file is returned per call,
            or null when there are no more matching files.

   The search may be aborted before completion, but make a final
   call with flag = 2 to clean up temp file. A new search with
   flag = 1 will also finish the cleanup.

   NOT THREAD SAFE - do not use in parallel threads

   '#' is used in place of '*' in comments below to prevent the
       compiler from interpreting /# and #/ as comment delimiters

   GNU find peculiarities:
     find /path/#      omits "." files
     find /path/       includes "." files
     find /path/#      recurses folders under /path/
     find /path/#.txt  does not recurse folders
     find /path/#/     finds all files under /path/
     find /path/#/#    finds files >= 1 folder level under /path/
     find /path/xxx#   never finds anything

   SearchWild uses simpler rules:
     '/' and '.' are treated like all other characters and match '#' and '?'
     no files are excluded except pure folders
     /path/#.txt finds all xxx.txt files under /path/ at all levels
     (because #.txt matches aaa.txt, /aaa/bbb.txt, etc.)

   Benchmark: search path: /usr/#   file: #.html   2 strings: #per prop#
              find 97 files from 209K files in /usr/#
              first time:  4.6 sec.
              second time:  1.5 sec.
              computer: 3.6 GHz core i7 with SSD disk

   Do not use to search files in /proc/# (causes infinite loop).

***/

ch * SearchWild(ch *wpath, int &uflag)
{
   static FILE    *fid = 0;
   static ch      buff[XFCC];
   static ch      wpath2[XFCC];
   static ch      command[XFCC];
   ch             *fcomm = "find \"%s\" -type f  2>/dev/null";
   int            cc, err;
   ch             *pp, *pp1, *pp2;

   if ((uflag == 1) || (uflag == 2)) {                                           //  first call or stop flag
      if (fid) pclose(fid);                                                      //  if file open, close it
      fid = 0;
      if (uflag == 2) return 0;                                                  //  stop flag, done
   }

   if (uflag == 1)                                                               //  first call flag
   {
      cc = strlen(wpath);
      if (cc == 0) return 0;
      if (cc > XFCC-20) zappcrash("SearchWild: wpath > XFCC");

      repl_Nstrs(wpath,wpath2,XFCC,"\"","\\\"","$","\\$",0);                     //  escape " and $ chars. in match pattern

      pp1 = strchr(wpath2,'*');                                                  //  find last wildcard in match pattern
      pp2 = strchr(wpath2,'?');
      pp = 0;
      if (pp1) {
         pp = pp1;
         if (pp2 && pp2 < pp1) pp = pp2;
      }
      else if (pp2) pp = pp2;
      if (pp) *pp = 0;                                                           //  terminate at first wildcard

      pp = strrchr(wpath2,'/');                                                  //  find last '/' in match pattern
      if (pp) pp[1] = 0;                                                         //  terminate after last '/'

      pp = zescape_quotes(wpath2);
      snprintf(command,XFCC,fcomm,pp);                                           //  result is input to find command
      zfree(pp);

      fid = popen(command,"r");                                                  //  start find command, get matching files
      if (! fid) zappcrash(strerror(errno));

      uflag = 763568954;                                                         //  begin search
   }

   if (uflag != 763568954) zappcrash("SearchWild, uflag invalid");

   while (true)
   {
      pp = fgets(buff,XFCC-2,fid);                                               //  next matching file
      if (! pp) {
         pclose(fid);                                                            //  no more
         fid = 0;
         return 0;
      }

      cc = strlen(pp);                                                           //  get rid of trailing \n
      pp[cc-1] = 0;

      err = MatchWild(wpath,pp);                                                 //  wildcard match?
      if (err) continue;                                                         //  no

      return pp;                                                                 //  return file
   }
}


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

    SearchWildCase  - wildcard file search - ignoring case
    Works like SearchWild() above, but case of file name is ignored.

    Actually, the trailing part of the path name is also case-insensitive,
    meaning that it is possible to get more matches than technically correct
    if folders like this are present:
       /AAA/BBB/.../filename
       /AAA/bbb/.../filename

***/

ch * SearchWildCase(ch *wpath, int &uflag)
{
   static FILE    *fid = 0;
   static ch      buff[XFCC];
   static ch      wpath2[XFCC];
   static ch      command[XFCC];
   ch             *fcomm = "find \"%s\" -type f  2>/dev/null";
   int            cc, err;
   ch             *pp, *pp1, *pp2;

   if ((uflag == 1) || (uflag == 2)) {                                           //  first call or stop flag
      if (fid) pclose(fid);                                                      //  if file open, close it
      fid = 0;
      if (uflag == 2) return 0;                                                  //  stop flag, done
   }

   if (uflag == 1)                                                               //  first call flag
   {
      cc = strlen(wpath);
      if (cc == 0) return 0;
      if (cc > XFCC-20) zappcrash("SearchWild: wpath > XFCC");

      repl_Nstrs(wpath,wpath2,XFCC,"\"","\\\"","$","\\$",0);                     //  escape " and $ chars. in match pattern

      pp1 = strchr(wpath2,'*');                                                  //  find last wildcard in match pattern
      pp2 = strchr(wpath2,'?');
      pp = 0;
      if (pp1) {
         pp = pp1;
         if (pp2 && pp2 < pp1) pp = pp2;
      }
      else if (pp2) pp = pp2;
      if (pp) *pp = 0;                                                           //  terminate at first wildcard

      pp = strrchr(wpath2,'/');                                                  //  find last '/' in match pattern
      if (pp) pp[1] = 0;                                                         //  terminate after last '/'

      pp = zescape_quotes(wpath2);
      snprintf(command,XFCC,fcomm,pp);                                           //  result is input to find command
      zfree(pp);

      fid = popen(command,"r");                                                  //  start find command, get matching files
      if (! fid) zappcrash(strerror(errno));

      uflag = 763568954;                                                         //  begin search
   }

   if (uflag != 763568954) zappcrash("SearchWild, uflag invalid");

   while (true)
   {
      pp = fgets(buff,XFCC-2,fid);                                               //  next matching file
      if (! pp) {
         pclose(fid);                                                            //  no more
         fid = 0;
         return 0;
      }

      cc = strlen(pp);                                                           //  get rid of trailing \n
      pp[cc-1] = 0;

      err = MatchWildCase(wpath,pp);                                             //  wildcard match? (ignore case)
      if (err) continue;                                                         //  no

      return pp;                                                                 //  return file
   }
}


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

   Find all files matching a given pattern (using glob() rules)

   int zfind(ch *pattern, ch **&flist, int &NF)

      pattern     pattern to match, with wildcards
      flist       list of files returned
      NF          count of files returned

   Returns 0 if OK, +N if error (errno is set).
   flist and flist[*] are subjects for zfree().

   zfind() works for files containing quotes (")
   dotfiles (/. and /..) are not included

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

int zfind(ch *pattern, ch **&flist, int &NF)
{
   ch       **zfind_filelist = 0;                                                //  list of filespecs returned
   int      globflags = GLOB_PERIOD;                                             //  include dotfiles
   int      ii, jj, err, cc;
   glob_t   globdata;
   ch       *pp;

   globdata.gl_pathc = 0;                                                        //  glob() setup
   globdata.gl_offs = 0;
   globdata.gl_pathc = 0;

   NF = 0;                                                                       //  empty output
   flist = 0;

   err = glob(pattern,globflags,null,&globdata);                                 //  find all matching files

   if (err) {
      if (err == GLOB_NOMATCH) err = 0;
      else if (err == GLOB_ABORTED) err = 1;
      else if (err == GLOB_NOSPACE) err = 2;
      else err = 3;
      if (err) Plog(0,"zfind() error: %d \n",err);
      globfree(&globdata);                                                       //  free glob memory
      return err;
   }

   NF = globdata.gl_pathc;
   if (! NF) {
      globfree(&globdata);
      return 0;
   }

   cc = NF * sizeof(ch *);
   zfind_filelist = (ch **) zmalloc(cc,"zfind");

   for (ii = jj = 0; ii < NF; ii++) {                                            //  loop found files
      pp = strrchr(globdata.gl_pathv[ii],'/');
      if (! pp) continue;
      if (strmatch(pp,"/.")) continue;                                           //  skip dotfiles
      if (strmatch(pp,"/..")) continue;
      zfind_filelist[jj++] = zstrdup(globdata.gl_pathv[ii],"zfind");             //  add file to output list
   }

   flist = zfind_filelist;                                                       //  return file list and count
   NF = jj;

   globfree(&globdata);                                                          //  free glob memory
   return 0;
}


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

//  perform a binary search on sorted list of integers
//  return matching element or -1 if not found
//  Benchmark: search a list of 10 million sorted integers
//             0.35 usecs.  3.3 GHz Core i5

int bsearch(int seekint, int nn, int list[])
{
   int      ii, jj, kk, rkk;

   ii = nn / 2;                                                                  //  next element to search
   jj = (ii + 1) / 2;                                                            //  next increment
   nn--;                                                                         //  last element
   rkk = 0;

   while (true)
   {
      kk = list[ii] - seekint;                                                   //  check element

      if (kk > 0)
      {
         ii -= jj;                                                               //  too high, go down
         if (ii < 0) return -1;
      }

      else if (kk < 0)
      {
         ii += jj;                                                               //  too low, go up
         if (ii > nn) return -1;
      }

      else if (kk == 0) return ii;                                               //  matched

      jj = jj / 2;                                                               //  reduce increment

      if (jj == 0)
      {
         jj = 1;                                                                 //  step by 1 element
         if (! rkk) rkk = kk;                                                    //  save direction
         else
         {
            if (rkk > 0) { if (kk < 0) return -1; }                              //  if change direction, fail
            else if (kk > 0) return -1;
         }
      }
   }
}


//  Perform a binary search on sorted set of records in memory.
//  Return matching record number (0 based) or -1 if not found.
//  Benchmark: search 10 million sorted records of 20 chars.
//             0.61 usecs.  3.3 GHz Core i5

int bsearch(ch *seekrec, ch *allrecs, int recl, int nrecs)
{
   int      ii, jj, kk, rkk;

   ii = nrecs / 2;                                                               //  next element to search
   jj = (ii + 1) / 2;                                                            //  next increment
   nrecs--;                                                                      //  last element
   rkk = 0;

   while (true)
   {
      kk = strcmp(allrecs+ii*recl,seekrec);                                      //  compare member rec to seek rec

      if (kk > 0)
      {
         ii -= jj;                                                               //  too high, go down in set
         if (ii < 0) return -1;
      }

      else if (kk < 0)
      {
         ii += jj;                                                               //  too low, go up in set
         if (ii > nrecs) return -1;
      }

      else if (kk == 0) return ii;                                               //  matched

      jj = jj / 2;                                                               //  reduce increment

      if (jj == 0)
      {
         jj = 1;                                                                 //  step by 1 element
         if (! rkk) rkk = kk;                                                    //  save direction
         else
         {
            if (rkk > 0) { if (kk < 0) return -1; }                              //  if change direction, fail
            else if (kk > 0) return -1;
         }
      }
   }
}


//  Perform a binary search on sorted set of pointers to records in memory.
//  Return matching record number (0 based) or -1 if not found.
//  The pointers are sorted in the order of the records starting at ch N.
//  The records need not be sorted.
//  The string length of seekrec is compared.

int bsearch(ch *seekrec, ch **allrecs, int N, int nrecs)
{
   int      ii, jj, kk, rkk;

   ii = nrecs / 2;                                                               //  next element to search
   jj = (ii + 1) / 2;                                                            //  next increment
   nrecs--;                                                                      //  last element
   rkk = 0;

   while (true)
   {
      kk = strcmp(allrecs[ii]+N,seekrec);                                        //  compare member rec to seek rec

      if (kk > 0)
      {
         ii -= jj;                                                               //  too high, go down in set
         if (ii < 0) return -1;
      }

      else if (kk < 0)
      {
         ii += jj;                                                               //  too low, go up in set
         if (ii > nrecs) return -1;
      }

      else if (kk == 0) return ii;                                               //  matched

      jj = jj / 2;                                                               //  reduce increment

      if (jj == 0)
      {
         jj = 1;                                                                 //  step by 1 element
         if (! rkk) rkk = kk;                                                    //  save direction
         else
         {
            if (rkk > 0) { if (kk < 0) return -1; }                              //  if change direction, fail
            else if (kk > 0) return -1;
         }
      }
   }
}


/********************************************************************************
   heap sort functions

   void HeapSort(int list[], int nn)
   void HeapSort(float flist[], int nn)
   void HeapSort(double dlist[], int nn)
      Sort list of nn integers, floats, or doubles.
      Numbers are sorted in ascending order.
      Uses 4 parallel threads for lists > 1000.

   void HeapSort(ch *plist[], int nn)
      Pointers are sorted in order of the strings they point to.
      The strings are not changed.

   void HeapSort(ch *plist1[], ch *plist2[], int nn)
      Sort two lists of pointers to two sets of strings.
      Both lists are sorted in order of the first set of strings.

   void HeapSort(ch *plist[], int nn, compfunc)
      Sort list of pointers to strings in user-defined order.
      Pointers are sorted, strings are not changed.
      Uses 4 parallel threads for lists > 1000.

   void HeapSort(ch *recs, int RL, int NR, compfunc)
      Sort an array of records in memory using a caller-supplied compare function.
         recs  pointer to 1st record in array
         RL    record length
         NR    no. of records

   int compfunc(ch *rec1, ch *rec2)
      compare rec1 to rec2, return -1 0 +1  if rec1 < = > rec2  in sort order.

   Benchmarks (4 GHz Core i5)
      100 million integers: 3.9 secs
      100 million floats: 5.2 secs
      100 million doubles: 6.1 secs
      52 million pointers to 20 character strings: 18.2 secs
      20 million records of 100 characters: 20.2 secs

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

#define SWAP(x,y) (temp = (x), (x) = (y), (y) = temp)


// ------------------------------------------------------------------------------

//  heapsort for array of integers

void adjust(int vv[], int n1, int n2)
{
   int   *bb, jj, kk, temp;

   bb = vv - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      if (kk < n2 && bb[kk] < bb[kk+1]) kk++;
      if (bb[jj] < bb[kk]) SWAP(bb[jj],bb[kk]);
      jj = kk;
      kk *= 2;
   }
}

void heapsort(int vv[], int nn)                                                  //  single thread version
{
   int   *bb, jj, temp;

   for (jj = nn/2; jj > 0; jj--) adjust(vv,jj,nn);

   bb = vv - 1;

   for (jj = nn-1; jj > 0; jj--)
   {
      SWAP(bb[1], bb[jj+1]);
      adjust(vv,1,jj);
   }
}

namespace HeapSort_int
{
   int         nn1, nn2, nn3, nn4;
   int         *vv1, *vv2, *vv3, *vv4;
   pthread_t   tid1, tid2, tid3, tid4;
   int         tt1 = 1, tt2 = 2, tt3 = 3, tt4 = 4;
}

void HeapSort(int vv[], int nn)                                                  //  4-thread version
{
   using namespace HeapSort_int;

   void * HeapSort_int_thread(void *arg);

   int   *vv9, *next;

   if (nn < 1000 || get_nprocs() < 2) {                                          //  small list or <2 SMPs
      heapsort(vv,nn);                                                           //  use one thread
      return;
   }

   nn1 = nn2 = nn3 = nn / 4;                                                     //  1st/2nd/3rd sub-list counts
   nn4 = nn - nn1 - nn2 - nn3;                                                   //  4th sub-list count

   vv1 = vv;                                                                     //  4 sub-list start positions
   vv2 = vv1 + nn1;
   vv3 = vv2 + nn2;
   vv4 = vv3 + nn3;

   tid1 = start_Jthread(HeapSort_int_thread,&tt1);                               //  sort the 4 sub-lists, parallel
   tid2 = start_Jthread(HeapSort_int_thread,&tt2);
   tid3 = start_Jthread(HeapSort_int_thread,&tt3);
   tid4 = start_Jthread(HeapSort_int_thread,&tt4);

   wait_Jthread(tid1);                                                           //  wait for 4 thread completions
   wait_Jthread(tid2);
   wait_Jthread(tid3);
   wait_Jthread(tid4);

   vv9 = (int *) malloc(nn * sizeof(int));                                       //  merge list, output list

   while (true)
   {
      next = 0;
      if (vv1) next = vv1;
      if (! next && vv2) next = vv2;
      if (! next && vv3) next = vv3;
      if (! next && vv4) next = vv4;
      if (! next) break;

      if (vv2 && *vv2 < *next) next = vv2;
      if (vv3 && *vv3 < *next) next = vv3;
      if (vv4 && *vv4 < *next) next = vv4;

      if (next == vv1) {
         vv1++;
         nn1--;
         if (! nn1) vv1 = 0;
      }

      else if (next == vv2) {
         vv2++;
         nn2--;
         if (! nn2) vv2 = 0;
      }

      else if (next == vv3) {
         vv3++;
         nn3--;
         if (! nn3) vv3 = 0;
      }

      else {
         vv4++;
         nn4--;
         if (! nn4) vv4 = 0;
      }

      *vv9 = *next;
      vv9++;
   }

   vv9 -= nn;
   memcpy(vv,vv9,nn * sizeof(int));                                              //  copy output list to input list
   free(vv9);                                                                    //  free output list

   return;
}

void * HeapSort_int_thread(void *arg)                                            //  thread function
{
   using namespace HeapSort_int;

   int tt = *((int *) arg);
   if (tt == 1) heapsort(vv1,nn1);
   if (tt == 2) heapsort(vv2,nn2);
   if (tt == 3) heapsort(vv3,nn3);
   if (tt == 4) heapsort(vv4,nn4);

   return 0;
}


// ------------------------------------------------------------------------------

//  heapsort for array of floats

void adjust(float vv[], int n1, int n2)
{
   float    *bb, temp;
   int      jj, kk;

   bb = vv - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      if (kk < n2 && bb[kk] < bb[kk+1]) kk++;
      if (bb[jj] < bb[kk]) SWAP(bb[jj],bb[kk]);
      jj = kk;
      kk *= 2;
   }
}

void heapsort(float vv[], int nn)                                                //  single thread version
{
   float    *bb, temp;
   int      jj;

   for (jj = nn/2; jj > 0; jj--) adjust(vv,jj,nn);

   bb = vv - 1;

   for (jj = nn-1; jj > 0; jj--)
   {
      SWAP(bb[1], bb[jj+1]);
      adjust(vv,1,jj);
   }
}

namespace HeapSort_float
{
   int         nn1, nn2, nn3, nn4;
   float       *vv1, *vv2, *vv3, *vv4;
   pthread_t   tid1, tid2, tid3, tid4;
   int         tt1 = 1, tt2 = 2, tt3 = 3, tt4 = 4;
}

void HeapSort(float vv[], int nn)                                                //  4-thread version
{
   using namespace HeapSort_float;

   void * HeapSort_float_thread(void *arg);

   float    *vv9, *next;

   if (nn < 1000 || get_nprocs() < 2) {                                          //  small list or <2 SMPs
      heapsort(vv,nn);                                                           //  use one thread
      return;
   }

   nn1 = nn2 = nn3 = nn / 4;                                                     //  1st/2nd/3rd sub-list counts
   nn4 = nn - nn1 - nn2 - nn3;                                                   //  4th sub-list count

   vv1 = vv;                                                                     //  4 sub-list start positions
   vv2 = vv1 + nn1;
   vv3 = vv2 + nn2;
   vv4 = vv3 + nn3;

   tid1 = start_Jthread(HeapSort_float_thread,&tt1);                             //  sort the 4 sub-lists, parallel
   tid2 = start_Jthread(HeapSort_float_thread,&tt2);
   tid3 = start_Jthread(HeapSort_float_thread,&tt3);
   tid4 = start_Jthread(HeapSort_float_thread,&tt4);

   wait_Jthread(tid1);                                                           //  wait for 4 thread completions
   wait_Jthread(tid2);
   wait_Jthread(tid3);
   wait_Jthread(tid4);

   vv9 = (float *) malloc(nn * sizeof(float));                                   //  merge list, output list

   while (true)
   {
      next = 0;
      if (vv1) next = vv1;
      if (! next && vv2) next = vv2;
      if (! next && vv3) next = vv3;
      if (! next && vv4) next = vv4;
      if (! next) break;

      if (vv2 && *vv2 < *next) next = vv2;
      if (vv3 && *vv3 < *next) next = vv3;
      if (vv4 && *vv4 < *next) next = vv4;

      if (next == vv1) {
         vv1++;
         nn1--;
         if (! nn1) vv1 = 0;
      }

      else if (next == vv2) {
         vv2++;
         nn2--;
         if (! nn2) vv2 = 0;
      }

      else if (next == vv3) {
         vv3++;
         nn3--;
         if (! nn3) vv3 = 0;
      }

      else {
         vv4++;
         nn4--;
         if (! nn4) vv4 = 0;
      }

      *vv9 = *next;
      vv9++;
   }

   vv9 -= nn;
   memcpy(vv,vv9,nn * sizeof(float));                                            //  copy output list to input list
   free(vv9);                                                                    //  free output list

   return;
}

void * HeapSort_float_thread(void *arg)                                          //  thread function
{
   using namespace HeapSort_float;

   int tt = *((int *) arg);
   if (tt == 1) heapsort(vv1,nn1);
   if (tt == 2) heapsort(vv2,nn2);
   if (tt == 3) heapsort(vv3,nn3);
   if (tt == 4) heapsort(vv4,nn4);

   return 0;
}


// ------------------------------------------------------------------------------

//  heapsort for array of doubles

void adjust(double vv[], int n1, int n2)
{
   double   *bb, temp;
   int      jj, kk;

   bb = vv - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      if (kk < n2 && bb[kk] < bb[kk+1]) kk++;
      if (bb[jj] < bb[kk]) SWAP(bb[jj],bb[kk]);
      jj = kk;
      kk *= 2;
   }
}

void heapsort(double vv[], int nn)                                               //  single thread version
{
   double   *bb, temp;
   int      jj;

   for (jj = nn/2; jj > 0; jj--) adjust(vv,jj,nn);

   bb = vv - 1;

   for (jj = nn-1; jj > 0; jj--)
   {
      SWAP(bb[1], bb[jj+1]);
      adjust(vv,1,jj);
   }
}

namespace HeapSort_double
{
   int         nn1, nn2, nn3, nn4;
   double      *vv1, *vv2, *vv3, *vv4;
   pthread_t   tid1, tid2, tid3, tid4;
   int         tt1 = 1, tt2 = 2, tt3 = 3, tt4 = 4;
}

void HeapSort(double vv[], int nn)                                               //  4-thread version
{
   using namespace HeapSort_double;

   void * HeapSort_double_thread(void *arg);

   double   *vv9, *next;

   if (nn < 1000 || get_nprocs() < 2) {                                          //  small list or <2 SMPs
      heapsort(vv,nn);                                                           //  use one thread
      return;
   }

   nn1 = nn2 = nn3 = nn / 4;                                                     //  1st/2nd/3rd sub-list counts
   nn4 = nn - nn1 - nn2 - nn3;                                                   //  4th sub-list count

   vv1 = vv;                                                                     //  4 sub-list start positions
   vv2 = vv1 + nn1;
   vv3 = vv2 + nn2;
   vv4 = vv3 + nn3;

   tid1 = start_Jthread(HeapSort_double_thread,&tt1);                            //  sort the 4 sub-lists, parallel
   tid2 = start_Jthread(HeapSort_double_thread,&tt2);
   tid3 = start_Jthread(HeapSort_double_thread,&tt3);
   tid4 = start_Jthread(HeapSort_double_thread,&tt4);

   wait_Jthread(tid1);                                                           //  wait for 4 thread completions
   wait_Jthread(tid2);
   wait_Jthread(tid3);
   wait_Jthread(tid4);

   vv9 = (double *) malloc(nn * sizeof(double));                                 //  merge list, output list

   while (true)
   {
      next = 0;
      if (vv1) next = vv1;
      if (! next && vv2) next = vv2;
      if (! next && vv3) next = vv3;
      if (! next && vv4) next = vv4;
      if (! next) break;

      if (vv2 && *vv2 < *next) next = vv2;
      if (vv3 && *vv3 < *next) next = vv3;
      if (vv4 && *vv4 < *next) next = vv4;

      if (next == vv1) {
         vv1++;
         nn1--;
         if (! nn1) vv1 = 0;
      }

      else if (next == vv2) {
         vv2++;
         nn2--;
         if (! nn2) vv2 = 0;
      }

      else if (next == vv3) {
         vv3++;
         nn3--;
         if (! nn3) vv3 = 0;
      }

      else {
         vv4++;
         nn4--;
         if (! nn4) vv4 = 0;
      }

      *vv9 = *next;
      vv9++;
   }

   vv9 -= nn;
   memcpy(vv,vv9,nn * sizeof(double));                                           //  copy output list to input list
   free(vv9);                                                                    //  free output list

   return;
}

void * HeapSort_double_thread(void *arg)                                         //  thread function
{
   using namespace HeapSort_double;

   int tt = *((int *) arg);
   if (tt == 1) heapsort(vv1,nn1);
   if (tt == 2) heapsort(vv2,nn2);
   if (tt == 3) heapsort(vv3,nn3);
   if (tt == 4) heapsort(vv4,nn4);

   return 0;
}


// ------------------------------------------------------------------------------

//  heapsort array of pointers to strings in ascending order of strings
//  pointers are sorted, strings are not changed.

void HeapSort(ch *vv[], int nn)
{
   HeapSort(vv,nn, (HeapSortUcomp *) strcmp);
   return;
}


// ------------------------------------------------------------------------------

//  Heapsort 2 lists of pointers to 2 parallel sets of strings
//    in ascending order of the first set of strings.
//  Both lists of pointers are sorted together in tandem.
//  Pointers are sorted, strings are not changed.

void adjust(ch *vv1[], ch *vv2[], int n1, int n2)
{
   ch       **bb1, **bb2, *temp;
   int      jj, kk;

   bb1 = vv1 - 1;
   bb2 = vv2 - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      if (kk < n2 && strcmp(bb1[kk],bb1[kk+1]) < 0) kk++;
      if (strcmp(bb1[jj],bb1[kk]) < 0) {
         SWAP(bb1[jj],bb1[kk]);
         SWAP(bb2[jj],bb2[kk]);
      }
      jj = kk;
      kk *= 2;
   }
}

void HeapSort(ch *vv1[], ch *vv2[], int nn)
{
   ch       **bb1, **bb2, *temp;
   int      jj;

   for (jj = nn/2; jj > 0; jj--) adjust(vv1,vv2,jj,nn);

   bb1 = vv1;
   bb2 = vv2;

   for (jj = nn-1; jj > 0; jj--)
   {
      SWAP(bb1[0], bb1[jj]);
      SWAP(bb2[0], bb2[jj]);
      adjust(vv1,vv2,1,jj);
   }
}


// ------------------------------------------------------------------------------

//  heapsort array of pointers to strings in user-defined order.
//  pointers are sorted, strings are not changed.

void adjust(ch *vv[], int n1, int n2, HeapSortUcomp fcomp)
{
   ch       **bb, *temp;
   int      jj, kk;

   bb = vv - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      if (kk < n2 && fcomp(bb[kk],bb[kk+1]) < 0) kk++;
      if (fcomp(bb[jj],bb[kk]) < 0) SWAP(bb[jj],bb[kk]);
      jj = kk;
      kk *= 2;
   }
}

void heapsort(ch *vv[], int nn, HeapSortUcomp fcomp)                             //  single thread version
{
   ch       **bb, *temp;
   int      jj;

   for (jj = nn/2; jj > 0; jj--) adjust(vv,jj,nn,fcomp);

   bb = vv;

   for (jj = nn-1; jj > 0; jj--)
   {
      SWAP(bb[0], bb[jj]);
      adjust(vv,1,jj,fcomp);
   }
}

namespace HeapSort_string
{
   int         nn1, nn2, nn3, nn4;
   ch          **vv1, **vv2, **vv3, **vv4;
   pthread_t   tid1, tid2, tid3, tid4;
   int         tt1 = 1, tt2 = 2, tt3 = 3, tt4 = 4;
   HeapSortUcomp  *ttfcomp;
}

void HeapSort(ch *vv[], int nn, HeapSortUcomp fcomp)                             //  4-thread version
{
   using namespace HeapSort_string;

   void * HeapSort_string_thread(void *arg);

   ch     **vv9, **next;

   if (nn < 1000 || get_nprocs() < 2) {                                          //  small list or <2 SMPs
      heapsort(vv,nn,fcomp);                                                     //  use one thread
      return;
   }

   nn1 = nn2 = nn3 = nn / 4;                                                     //  1st/2nd/3rd sub-list counts
   nn4 = nn - nn1 - nn2 - nn3;                                                   //  4th sub-list count

   vv1 = vv;                                                                     //  4 sub-list start positions
   vv2 = vv1 + nn1;
   vv3 = vv2 + nn2;
   vv4 = vv3 + nn3;

   ttfcomp = fcomp;

   tid1 = start_Jthread(HeapSort_string_thread,&tt1);                            //  sort the 4 sub-lists, parallel
   tid2 = start_Jthread(HeapSort_string_thread,&tt2);
   tid3 = start_Jthread(HeapSort_string_thread,&tt3);
   tid4 = start_Jthread(HeapSort_string_thread,&tt4);

   wait_Jthread(tid1);                                                           //  wait for 4 thread completions
   wait_Jthread(tid2);
   wait_Jthread(tid3);
   wait_Jthread(tid4);

   vv9 = (ch **) malloc(nn * sizeof(ch *));                                      //  merge list, output list

   while (true)
   {
      next = 0;
      if (vv1) next = vv1;
      if (! next && vv2) next = vv2;
      if (! next && vv3) next = vv3;
      if (! next && vv4) next = vv4;
      if (! next) break;

      if (vv2 && ttfcomp(*vv2,*next) < 0) next = vv2;
      if (vv3 && ttfcomp(*vv3,*next) < 0) next = vv3;
      if (vv4 && ttfcomp(*vv4,*next) < 0) next = vv4;

      if (next == vv1) {
         vv1++;
         nn1--;
         if (! nn1) vv1 = 0;
      }

      else if (next == vv2) {
         vv2++;
         nn2--;
         if (! nn2) vv2 = 0;
      }

      else if (next == vv3) {
         vv3++;
         nn3--;
         if (! nn3) vv3 = 0;
      }

      else {
         vv4++;
         nn4--;
         if (! nn4) vv4 = 0;
      }

      *vv9 = *next;
      vv9++;
   }

   vv9 -= nn;
   memcpy(vv,vv9,nn * sizeof(ch *));                                             //  copy output list to input list
   free(vv9);                                                                    //  free output list

   return;
}

void * HeapSort_string_thread(void *arg)                                         //  thread function
{
   using namespace HeapSort_string;

   int tt = *((int *) arg);
   if (tt == 1) heapsort(vv1,nn1,ttfcomp);
   if (tt == 2) heapsort(vv2,nn2,ttfcomp);
   if (tt == 3) heapsort(vv3,nn3,ttfcomp);
   if (tt == 4) heapsort(vv4,nn4,ttfcomp);

   return 0;
}


// ------------------------------------------------------------------------------

//  heapsort for array of records,
//  using caller-supplied record compare function.
//  HeapSortUcomp returns [ -1 0 +1 ]  for  rec1 [ < = > ] rec2
//  method: build array of pointers and sort these, then
//  use this sorted array to re-order the records at the end.

void adjust(ch *recs, int RL, int n1, int n2, int *vv1, HeapSortUcomp fcomp)
{
   int      *bb, jj, kk, temp;
   ch       *rec1, *rec2;

   bb = vv1 - 1;
   jj = n1;
   kk = n1 * 2;

   while (kk <= n2)
   {
      rec1 = recs + RL * bb[kk];
      rec2 = recs + RL * bb[kk+1];
      if (kk < n2 && fcomp(rec1,rec2) < 0) kk++;
      rec1 = recs + RL * bb[jj];
      rec2 = recs + RL * bb[kk];
      if (fcomp(rec1,rec2) < 0) SWAP(bb[jj],bb[kk]);
      jj = kk;
      kk *= 2;
   }
}

void HeapSort(ch *recs, int RL, int NR, HeapSortUcomp fcomp)
{
   int      *bb, jj, kk, temp, flag;
   int      *vv1, *vv2;                                                          //  make reentrant
   ch       *vvrec;

   vv1 = (int *) malloc((NR+1) * sizeof(int));
   for (jj = 0; jj < NR; jj++) vv1[jj] = jj;

   for (jj = NR/2; jj > 0; jj--) adjust(recs,RL,jj,NR,vv1,fcomp);

   bb = vv1 - 1;

   for (jj = NR-1; jj > 0; jj--)
   {
      SWAP(bb[1], bb[jj+1]);
      adjust(recs,RL,1,jj,vv1,fcomp);
   }

   vv2 = (int *) malloc((NR+1) * sizeof(int));
   for (jj = 0; jj < NR; jj++) vv2[vv1[jj]] = jj;

   vvrec = (ch *) malloc(RL);
   flag = 1;
   while (flag)
   {
      flag = 0;
      for (jj = 0; jj < NR; jj++)
      {
         kk = vv2[jj];
         if (kk == jj) continue;
         memmove(vvrec,recs+jj*RL,RL);
         memmove(recs+jj*RL,recs+kk*RL,RL);
         memmove(recs+kk*RL,vvrec,RL);
         SWAP(vv2[jj],vv2[kk]);
         flag = 1;
      }
   }

   free(vv1);
   free(vv2);
   free(vvrec);
}


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

   int MemSort (ch *RECS, int RL, int NR, int KEYS[][3], int NK)

   RECS is an array of records, to be sorted in-place.
   (record length = RL, record count = NR)

   KEYS[NK][3]  is an integer array defined as follows:
        [N][0]    starting position of Nth key field in RECS
        [N][1]    length of Nth key field in RECS
        [N][2]    type of sort for Nth key:
                    1 = ch ascending
                    2 = ch descending
                    3 = int*4 ascending
                    4 = int*4 descending
                    5 = float*4 ascending
                    6 = float*4 descending
                    7 = float*8 ascending (double)
                    8 = float*8 descending
   Benchmark: 10 million recs of 80 bytes with 4 sort keys:
              10.8 secs (4 GHz Core i5).

***/

int MemSortComp(ch *rec1, ch *rec2);
int MemSortKeys[10][3], MemSortNK;

int MemSort(ch *RECS, int RL, int NR, int KEYS[][3], int NK)
{
   int   ii;

   if (NR < 2) return 1;

   if (NK > 10) zappcrash("MemSort, bad NK");
   if (NK < 1) zappcrash("MemSort, bad NK");

   MemSortNK = NK;

   for (ii = 0; ii < NK; ii++)
   {
      MemSortKeys[ii][0] = KEYS[ii][0];
      MemSortKeys[ii][1] = KEYS[ii][1];
      MemSortKeys[ii][2] = KEYS[ii][2];
   }

   HeapSort(RECS,RL,NR,MemSortComp);
   return 1;
}

int MemSortComp(ch *rec1, ch *rec2)
{
   int         ii, stat, kpos, ktype, kleng;
   int         inum1, inum2;
   float       rnum1, rnum2;
   double      dnum1, dnum2;
   ch          *p1, *p2;

   for (ii = 0; ii < MemSortNK; ii++)                                            //  loop each key
   {
      kpos = MemSortKeys[ii][0];                                                 //  relative position
      kleng = MemSortKeys[ii][1];                                                //  length
      ktype = MemSortKeys[ii][2];                                                //  type

      p1 = rec1 + kpos;                                                          //  absolute position
      p2 = rec2 + kpos;

      switch (ktype)
      {
         case 1:                                                                 //  ch ascending
            stat = strncmp(p1,p2,kleng);                                         //  compare 2 key values
            if (stat) return stat;                                               //  + if rec1 > rec2, - if <
            break;                                                               //  2 keys are equal, check next key

         case 2:                                                                 //  ch descending
            stat = strncmp(p1,p2,kleng);
            if (stat) return -stat;
            break;

         case 3:                                                                 //  int ascending
            memmove(&inum1,p1,4);
            memmove(&inum2,p2,4);
            if (inum1 > inum2) return 1;
            if (inum1 < inum2) return -1;
            break;

         case 4:                                                                 //  int descending
            memmove(&inum1,p1,4);
            memmove(&inum2,p2,4);
            if (inum1 > inum2) return -1;
            if (inum1 < inum2) return 1;
            break;

         case 5:                                                                 //  float ascending
            memmove(&rnum1,p1,4);
            memmove(&rnum2,p2,4);
            if (rnum1 > rnum2) return 1;
            if (rnum1 < rnum2) return -1;
            break;

         case 6:                                                                 //  float descending
            memmove(&rnum1,p1,4);
            memmove(&rnum2,p2,4);
            if (rnum1 > rnum2) return -1;
            if (rnum1 < rnum2) return 1;
            break;

         case 7:                                                                 //  double ascending
            memmove(&dnum1,p1,8);
            memmove(&dnum2,p2,8);
            if (dnum1 > dnum2) return 1;
            if (dnum1 < dnum2) return -1;
            break;

         case 8:                                                                 //  double descending
            memmove(&dnum1,p1,8);
            memmove(&dnum2,p2,8);
            if (dnum1 > dnum2) return -1;
            if (dnum1 < dnum2) return 1;
            break;

         default:                                                                //  key type not 1-8
            zappcrash("MemSort, bad KEYS sort type");
      }
   }

   return 0;                                                                     //  records match on all keys
}


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

//  test if an integer value matches any in a list of values
//  returns the matching value or zero if nothing matches
//  list of values must end with zero
//  zero cannot be one of the values to match

int zmember(int testval, int matchval1, ...)
{
   va_list     arglist;
   int         matchval;

   va_start(arglist,matchval1);
   matchval = matchval1;

   while (matchval)
   {
      if (testval == matchval) break;
      matchval = va_arg(arglist,int);
      if (! matchval || matchval == (int) 0x100000000);                          //  ARM bug
   }

   va_end(arglist);
   return matchval;
}


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

   Hash Table class

   HashTab(int cc, int cap);                       constructor
   ~HashTab();                                     destructor
   int Add(ch *string);                            add a new string
   int Del(ch *string);                            delete a string
   int Find(ch *string);                           find a string
   int GetCount() { return count; }                get string count
   int GetNext(int &first, ch *string);            get first/next string
   int Dump();                                     dump hash table to std. output

   constructor: cc = string length of table entries, cap = table capacity
   cap should be set 30% higher than needed to reduce collisions and improve speed

   Benchmark: 0.056 usec. to find 19 ch string in a table of 100,000
              which is 80% full.    3.3 GHz Core i5

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

//  static members (robust for tables up to 60% full)

int HashTab::tries1 = 100;                                                       //  Add() tries
int HashTab::tries2 = 200;                                                       //  Find() tries


HashTab::HashTab(int _cc, int _cap)                                              //  constructor
{
   cc = 4 * (_cc + 4) / 4;                                                       //  + 1 + mod 4 length
   cap = _cap;
   int len = cc * cap;
   table = new ch [len];
   if (! table) zappcrash("HashTab() new %d fail",len,null);
   memset(table,0,len);
}


HashTab::~HashTab()                                                              //  destructor
{
   delete [] table;
   table = 0;
}


//  Add a new string to table

int HashTab::Add(ch *string)
{
   int   pos, fpos, tries;

   pos = strHash(string,cap);                                                    //  get random position
   pos = pos * cc;

   for (tries = 0, fpos = -1; tries < tries1; tries++, pos += cc)                //  find next free slot at/after position
   {
      if (pos >= cap * cc) pos = 0;                                              //  last position wraps to 1st

      if (! table[pos])                                                          //  empty slot: string not found
      {
         if (fpos != -1) pos = fpos;                                             //  use prior deleted slot if there
         strncpy(table+pos,string,cc);                                           //  insert new string
         table[pos+cc-1] = 0;                                                    //  insure null terminator
         return (pos/cc);                                                        //  return rel. table entry
      }

      if (table[pos] == -1)                                                      //  deleted slot
      {
         if (fpos == -1) fpos = pos;                                             //  remember 1st one found
         continue;
      }

      if (strmatch(string,table+pos)) return -2;                                 //  string already present
   }

   return -3;                                                                    //  table full (tries1 exceeded)
}


//  Delete a string from table

int HashTab::Del(ch *string)
{
   int   pos, tries;

   pos = strHash(string,cap);                                                    //  get random position
   pos = pos * cc;

   for (tries = 0; tries < tries2; tries++, pos += cc)                           //  search for string at/after position
   {
      if (pos >= cap * cc) pos = 0;                                              //  last position wraps to 1st

      if (! table[pos]) return -1;                                               //  empty slot, string not found

      if (strmatch(string,table+pos))                                            //  string found
      {
         table[pos] = -1;                                                        //  delete table entry
         return (pos/cc);                                                        //  return rel. table entry
      }
   }

   zappcrash("HashTab::Del() fail",null);                                        //  exceed tries2, must not happen
   return 0;                                                                     //  (table too full to function)
}


//  Find a table entry.

int HashTab::Find(ch *string)
{
   int   pos, tries;

   pos = strHash(string,cap);                                                    //  get random position
   pos = pos * cc;

   for (tries = 0; tries < tries2; tries++, pos += cc)                           //  search for string at/after position
   {
      if (pos >= cap * cc) pos = 0;                                              //  last position wraps to 1st
      if (! table[pos]) return -1;                                               //  empty slot, string not found
      if (strmatch(string,table+pos)) return (pos/cc);                           //  string found, return rel. entry
   }

   zappcrash("HashTab::Find() fail",null);                                       //  cannot happen
   return 0;
}


//  return first or next table entry

int HashTab::GetNext(int &ftf, ch *string)
{
   static int    pos;

   if (ftf)                                                                      //  initial call
   {
      pos = 0;
      ftf = 0;
   }

   while (pos < (cap * cc))
   {
      if ((table[pos] == 0) || (table[pos] == -1))                               //  empty or deleted slot
      {
         pos += cc;
         continue;
      }

      strcpy(string,table+pos);                                                  //  return string
      pos += cc;
      return 1;
   }

   return -4;                                                                    //  EOF
}


int HashTab::Dump()
{
   int   ii, pos;

   for (ii = 0; ii < cap; ii++)
   {
      pos = ii * cc;

      if (table[pos] && table[pos] != -1)
         Plog(0,"%d, %s \n", ii, table + pos);

      if (table[pos] == -1)
         Plog(0,"%d, deleted \n", pos);
   }

   return 1;
}


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

   list processing functions                                                     //  replace pvlist functions

   typedef struct {                             list data type
      int      count;                           count of member strings
      ch       **mber;                          member strings, null == no members
   }  zlist_t;

   zlist_t   *zlist;

   zlist = zlist_new(N)                            make new zlist with N null members
   void zlist_free(zlist)                          delete zlist, free memory
   void zlist_dump(zlist)                          dump zlist to stdout
   N = zlist_count(zlist)                          get member count (including null entries)
   string = zlist_get(zlist,Nth)                   get Nth member
   void zlist_put(zlist,string,Nth)                put Nth member (replace)
   void zlist_insert(zlist,string,Nth)             insert member (count += 1)
   void zlist_remove(zlist,Nth)                    remove member (count -= 1)
   void zlist_purge(zlist);                        purge zlist of null members
   void zlist_clear(zlist_t *zlist, int Nth);      clear zlist from Nth member to end
   err = zlist_add(zlist,string,Funiq)             add member at first null or append (if unique)
   err = zlist_append(zlist,string,Funiq)          append new member (if unique)
   err = zlist_prepend(zlist,string,Funiq)         prepend new member (if unique)
   Nth = zlist_find(zlist,string,posn);            find next matching zlist member at/after posn
   Nth = zlist_findwild(zlist,wstring,posn);       same as above, but wildcard string match
   zlist2 = zlist_copy(zlist1)                     copy zlist
   zlist3 = zlist_insert(zlist1,zlist2,Nth)        insert zlist2 into zlist1 at Nth posn
   zlist3 = zlist_remove(zlist1,zlist2)            remove all members of zlist2 from zlist1
   void zlist_sort(zlist)                          sort zlist ascending
   void zlist_sort(zlist,ccfunc)                   sort zlist using caller compare function
   string = zlist_choose(zlist);                   popup menu - user choice of member
   err = zlist_to_file(zlist,filename)             make file from zlist
   zlist = zlist_from_file(filename)               make zlist from file

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


//  create zlist with 'count' empty members

zlist_t * zlist_new(int count)
{
   zlist_t *zlist = (zlist_t *) zmalloc(sizeof(zlist_t),"zlist");
   zlist->count = count;
   if (count > 0)
      zlist->mber = (ch **) zmalloc(count * sizeof(ch *),"zlist");
   for (int ii = 0; ii < count; ii++)
      zlist->mber[ii] = null;
   return zlist;
}


//  delete a zlist

void zlist_free(zlist_t *zlist)
{
   for (int ii = 0; ii < zlist->count; ii++)
      if (zlist->mber[ii])
         zfree(zlist->mber[ii]);
   if (zlist->mber) zfree(zlist->mber);
   zlist->count = 0;
   zfree(zlist);
   return;
}


//  dump zlist to stdout

void zlist_dump(zlist_t *zlist)
{
   Plog(0,"count: %d \n",zlist->count);
   for (int ii = 0; ii < zlist->count; ii++)
      Plog(0,"%5d  %s \n",ii,zlist->mber[ii]);
   Plog(0,"\n");
   return;
}


//  get zlist member count

int zlist_count(zlist_t *zlist)
{
   return zlist->count;
}


//  get a zlist member

ch * zlist_get(zlist_t *zlist, int Nth)
{
   if (Nth < 0 || Nth >= zlist->count)
      zappcrash("zlist_get() invalid Nth: %d",Nth);
   return zlist->mber[Nth];
}


//  put a zlist member (replace existing) (null allowed)

void zlist_put(zlist_t *zlist, ch *string, int Nth)
{
   if (Nth < 0 || Nth >= zlist->count)
      zappcrash("zlist_put() invalid Nth: %d",Nth);
   if (zlist->mber[Nth]) zfree(zlist->mber[Nth]);
   if (string) zlist->mber[Nth] = zstrdup(string,"zlist");
   else zlist->mber[Nth] = 0;
   return;
}


//  insert new zlist member (count increases)
//  new member is Nth member, old Nth member is Nth+1
//  if Nth > last + 1, null members are added in-between

void zlist_insert(zlist_t *zlist, ch *string, int Nth)
{
   int      count, newcount;
   int      ii1, ii2, cc;
   ch       **newmber;

   if (Nth < 0) zappcrash("zlist_insert() invalid Nth: %d",Nth);
   count = zlist->count;
   if (Nth < count) newcount = count + 1;
   else newcount = Nth + 1;
   newmber = (ch **) zmalloc(newcount * sizeof(ch *),"zlist");

   if (Nth > 0) {                                                                //  copy 0 - Nth-1
      ii1 = 0;
      ii2 = Nth;
      if (Nth > count) ii2 = count;
      cc = (ii2 - ii1) * sizeof(ch *);
      memcpy(newmber,zlist->mber,cc);
   }

   newmber[Nth] = zstrdup(string,"zlist");                                       //  insert Nth

   if (Nth < count) {                                                            //  copy Nth - last
      ii1 = Nth;
      ii2 = count;
      cc = (ii2 - ii1) * sizeof(ch *);
      memcpy(newmber+ii1+1,zlist->mber+ii1,cc);
   }

   if (zlist->mber) zfree(zlist->mber);
   zlist->mber = newmber;
   zlist->count = newcount;
   return;
}


//  remove a zlist member (count -= 1)

void zlist_remove(zlist_t *zlist, int Nth)
{
   int      newcount, cc;
   ch       **newmber;

   if (Nth < 0 || Nth >= zlist->count)
      zappcrash("zlist_remove() invalid Nth: %d",Nth);

   newcount = zlist->count - 1;
   if (newcount)
      newmber = (ch **) zmalloc(newcount * sizeof(ch *),"zlist");
   else newmber = 0;

   if (Nth > 0) {                                                                //  copy 0 - Nth-1
      cc = Nth * sizeof(ch *);
      memcpy(newmber,zlist->mber,cc);
   }

   if (zlist->mber[Nth]) zfree(zlist->mber[Nth]);                                //  remove Nth

   if (Nth < newcount) {                                                         //  copy Nth+1 - last
      cc = (newcount - Nth) * sizeof(ch *);
      memcpy(newmber+Nth,zlist->mber+Nth+1,cc);
   }

   zfree(zlist->mber);
   zlist->mber = newmber;
   zlist->count = newcount;
   return;
}


//  purge zlist of all null members and reset count

void zlist_purge(zlist_t *zlist)
{
   int      ii, jj;
   ch       **mber;

   for (ii = jj = 0; ii < zlist->count; ii++)
      if (zlist->mber[ii]) jj++;

   if (jj) mber = (ch **) zmalloc(jj * sizeof(ch *),"zlist");
   else mber = 0;

   for (ii = jj = 0; ii < zlist->count; ii++) {
      if (zlist->mber[ii]) {
         mber[jj] = zlist->mber[ii];
         jj++;
      }
   }

   zlist->count = jj;
   zfree(zlist->mber);
   zlist->mber = mber;
   return;
}


//  clear zlist members from Nth to end

void zlist_clear(zlist_t *zlist, int Nth)
{
   int      ii;
   ch       **mber = 0;

   if (Nth >= zlist_count(zlist)) return;

   if (Nth > 0) mber = (ch **) zmalloc(Nth * sizeof(ch *),"zlist");              //  remaining members

   for (ii = 0; ii < Nth; ii++)                                                  //  copy remaining members
      mber[ii] = zlist->mber[ii];

   for (ii = Nth; ii < zlist_count(zlist); ii++)                                 //  free deleted members
      zfree(zlist->mber[ii]);

   zfree(zlist->mber);
   zlist->mber = mber;                                                           //  null if empty list
   zlist->count = Nth;
   return;
}


//  add new member at first null position, or append (if unique)
//  return 0 if OK, 1 if not unique

int zlist_add(zlist_t *zlist, ch *string, int Funiq)
{
   int      ii;

   if (Funiq && zlist_find(zlist,string,0) >= 0) return 1;
   for (ii = 0; ii < zlist->count; ii++)
      if (! zlist->mber[ii]) break;
   if (ii < zlist->count) {
      zlist->mber[ii] = zstrdup(string,"zlist");
      return 0;
   }
   return zlist_append(zlist,string,Funiq);
}


//  append new member at end (if unique)
//  return 0 if OK, 1 if not unique

int zlist_append(zlist_t *zlist, ch *string, int Funiq)
{
   if (Funiq && zlist_find(zlist,string,0) >= 0) return 1;
   zlist_insert(zlist,string,zlist->count);
   return 0;
}


//  prepend new member at posn 0 (if unique)
//  return 0 if OK, 1 if not unique

int zlist_prepend(zlist_t *zlist, ch *string, int Funiq)
{
   if (Funiq && zlist_find(zlist,string,0) >= 0) return 1;
   zlist_insert(zlist,string,0);
   return 0;
}


//  find next matching zlist member at/from given posn

int zlist_find(zlist_t *zlist, ch *string, int posn)
{
   if (posn < 0 || posn >= zlist->count) return -1;
   for (int ii = posn; ii < zlist->count; ii++) {
      if (zlist->mber[ii])
         if (strmatch(string,zlist->mber[ii])) return ii;
   }
   return -1;
}


//  find next matching zlist member at/from given posn (wildcard match)

int zlist_findwild(zlist_t *zlist, ch *wstring, int posn)
{
   if (posn < 0 || posn >= zlist->count) return -1;
   for (int ii = posn; ii < zlist->count; ii++) {
      if (zlist->mber[ii])
         if (MatchWild(wstring,zlist->mber[ii]) == 0) return ii;
   }
   return -1;
}


//  copy a zlist

zlist_t * zlist_copy(zlist_t *zlist1)
{
   zlist_t *zlist2 = zlist_new(zlist1->count);
   for (int ii = 0; ii < zlist2->count; ii++)
      if (zlist1->mber[ii])
         zlist2->mber[ii] = zstrdup(zlist1->mber[ii],"zlist");
   return zlist2;
}


//  insert zlist2 into zlist1 at Nth position
//  use Nth = -1 to insert at the end (append)

zlist_t * zlist_insert_zlist(zlist_t *zlist1, zlist_t *zlist2, int Nth)
{
   int   ii;
   int   nn1 = zlist1->count;                   //  zlist to receive
   int   nn2 = zlist2->count;                   //  zlist to insert
   int   nn3 = nn1 + nn2;                       //  output zlist

   if (Nth < 0) Nth = nn1;                      //  append to end of zlist1
   if (Nth > nn1) nn3 = Nth + nn2;              //  append with missing members in-between

   zlist_t *zlist3 = zlist_new(nn3);

   for (ii = 0; ii < Nth; ii++)                                                  //  0 to Nth-1
      if (ii < nn1 && zlist1->mber[ii])
         zlist3->mber[ii] = zstrdup(zlist1->mber[ii],"zlist");
   for (ii = Nth; ii < Nth + nn2; ii++)                                          //  Nth to Nth + nn2-1
      if (zlist2->mber[ii-Nth])
         zlist3->mber[ii] = zstrdup(zlist2->mber[ii-Nth],"zlist");
   for (ii = Nth + nn2; ii < nn3; ii++)                                          //  Nth + nn2 to nn3-1
      if (ii-nn2 < nn1 && zlist1->mber[ii-nn2])
         zlist3->mber[ii] = zstrdup(zlist1->mber[ii-nn2],"zlist");

   return zlist3;
}


//  remove all members of zlist2 from zlist1

zlist_t * zlist_remove(zlist_t *zlist1, zlist_t *zlist2)
{
   int   ii, jj;
   int   nn2 = zlist2->count;

   zlist_t *zlist3 = zlist_copy(zlist1);                                         //  copy input zlist

   for (ii = 0; ii < nn2; ii++) {
      jj = zlist_find(zlist3,zlist_get(zlist2,ii),0);                            //  find zlist2 member in zlist3
      if (jj >= 0) zlist_put(zlist3,null,jj);                                    //  if found, replace with null
   }

   zlist_purge(zlist3);                                                          //  purge null entries
   return zlist3;
}


//  sort zlist ascending

void zlist_sort(zlist_t *zlist)
{
   HeapSort(zlist->mber,zlist->count);
   return;
}


//  sort zlist via caller compare function

void zlist_sort(zlist_t *zlist, int ccfunc(ch *, ch *))
{
   HeapSort(zlist->mber,zlist->count,ccfunc);
   return;
}


//  popup menu, user choice of zlist member

ch *  zlist_choose_choice = 0;

ch * zlist_choose(zlist_t *zlist)                                                //  24.70
{
   void zlist_choose_choose(GtkWidget *, ch *);

   static GtkWidget  *popmenu;
   static int        busy = 0;
   int               nl;
   ch                *member;
   
   if (busy) {
      printf("zlist_choose() re-entry \n");
      zlist_choose_choice = "NONE";                                              //  compensate loop problem
      gtk_widget_destroy(popmenu);                                               //  24.70
      return 0;
   }
   
   busy = 1;
   
   nl = zlist_count(zlist);
   if (! nl) return 0;
   
   popmenu = create_popmenu();
   
   for (int ii = 0; ii < nl; ii++)
   {
      member = zlist_get(zlist,ii);
      if (member) add_popmenu_item(popmenu,member,zlist_choose_choose,0,0);
   }
   
   add_popmenu_item(popmenu,"CLOSE",zlist_choose_choose,0,0);
   
   zlist_choose_choice = 0;

   popup_menu(0,popmenu);
   
   while (! zlist_choose_choice) zmainsleep(0.2);                                //  loop forever if click outside menu

   if (strmatch(zlist_choose_choice,"NONE")) zlist_choose_choice = 0;
   
   busy = 0;
   return zlist_choose_choice;
}


//  zlist_choose response function

void zlist_choose_choose(GtkWidget *, ch *choice)
{
   if (! choice || strmatch(choice,"CLOSE")) 
      zlist_choose_choice = "NONE";
   else zlist_choose_choice = choice;
   return;
}


//  make file from zlist

int zlist_to_file(zlist_t *zlist, ch *filename)
{
   int      ii, err;

   FILE *fid = fopen(filename,"w");
   if (! fid) return errno;
   for (ii = 0; ii < zlist->count; ii++)
      if (zlist->mber[ii])
         fprintf(fid,"%s\n",zlist->mber[ii]);
   err = fclose(fid);
   if (err) return errno;
   else return 0;
}


//  make zlist from file
//  performance with SSD: over 100 MB/sec.

zlist_t * zlist_from_file(ch *filename)
{
   FILE     *fid;
   zlist_t  *zlist;
   int      ii, count = 0;
   ch       *pp, buff[XFCC];

   fid = fopen(filename,"r");                                                    //  count recs in file
   if (! fid) return 0;                                                          //  this adds 40% to elapsed time
   while (true) {
      pp = fgets(buff,XFCC,fid);
      if (! pp) break;
      count++;
   }
   fclose(fid);

   fid = fopen(filename,"r");
   if (! fid) return 0;
   zlist = zlist_new(count);                                                     //  create zlist
   for (ii = 0; ii < count; ii++) {
      pp = fgets_trim(buff,XFCC,fid);
      if (! pp) break;
      zlist->mber[ii] = zstrdup(buff,"zlist");
   }
   fclose(fid);

   return zlist;
}


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

//  Random number generators with explicit context
//  and improved randomness over a small series.
//  Benchmark: lrandz 0.012 usec  drandz 0.014 usec  3.3 GHz Core i5
//  (srand() % range) is much slower.

int lrandz(int64 *seed)                                                          //  returns 0 to 0x7fffffff
{
   *seed = *seed ^ (*seed << 17);
   *seed = *seed ^ (*seed << 20);
   return nrand48((unsigned int16 *) seed);
}

int lrandz()                                                                     //  implicit seed, repeatable sequence
{
   static int64   seed = 12345678;
   return lrandz(&seed);
}

double drandz(int64 *seed)                                                       //  returns 0.0 to 0.99999...
{
   *seed = *seed ^ (*seed << 17);
   *seed = *seed ^ (*seed << 20);
   return erand48((unsigned int16 *) seed);
}

double drandz()                                                                  //  automatic seed, volatile
{
   static int64 seed = get_seconds();
   return drandz(&seed);
}


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

   spline1: define a curve using a set of data points (x and y values)
   spline2: for a given x-value, return a y-value fitting the curve

   For spline1, the no. of curve-defining points must be < 100.
   For spline2, the given x-value must be within the range defined in spline1.

   The algorithm was taken from the book "Numerical Recipes"
   (Cambridge University Press) and converted from Fortran to C++.

***/

namespace splinedata
{
   int      nn;
   float    px1[100], py1[100], py2[100];
}


void spline1(int dnn, float *dx1, float *dy1)
{
   using namespace splinedata;

   float    sig, p, u[100];
   int      ii;

   nn = dnn;
   if (nn > 100) zappcrash("spline1(), > 100 data points");

   for (ii = 0; ii < nn; ii++)
   {
      px1[ii] = dx1[ii];
      py1[ii] = dy1[ii];
      if (ii && px1[ii] <= px1[ii-1])
         zappcrash("spline1(), x-value not increasing");
   }

   py2[0] = u[0] = 0;

   for (ii = 1; ii < nn-1; ii++)
   {
      sig = (px1[ii] - px1[ii-1]) / (px1[ii+1] - px1[ii-1]);
      p = sig * py2[ii-1] + 2;
      py2[ii] = (sig - 1) / p;
      u[ii] = (6 * ((py1[ii+1] - py1[ii]) / (px1[ii+1] - px1[ii]) - (py1[ii] - py1[ii-1])
            / (px1[ii] - px1[ii-1])) / (px1[ii+1] - px1[ii-1]) - sig * u[ii-1]) / p;
   }

   py2[nn-1] = 0;

   for (ii = nn-2; ii >= 0; ii--)
      py2[ii] = py2[ii] * py2[ii+1] + u[ii];

   return;
}


float  spline2(float x)
{
   using namespace splinedata;

   int      kk, klo = 0, khi = nn-1;
   float    h, a, b, y;

   while (khi - klo > 1)
   {
      kk = (khi + klo) / 2;
      if (px1[kk] > x) khi = kk;
      else klo = kk;
   }

   h = px1[khi] - px1[klo];
   a = (px1[khi] - x) / h;
   b = (x - px1[klo]) / h;
   y = a * py1[klo] + b * py1[khi] + ((a*a*a - a) * py2[klo]
                                   + (b*b*b - b) * py2[khi]) * (h*h) / 6;

   return y;
}


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

//  Add text strings to a FIFO queue, retrieve text strings.
//  Can be used by one or two threads.
//  thread 1: open queue, get strings, close queue.
//  thread 2: put strings into queue.


//  create and initialize Qtext queue, empty status

void Qtext_open(Qtext *qtext, int cap)
{
   int      cc;

   qtext->qcap = cap;
   qtext->qnewest = -1;
   qtext->qoldest = -1;
   qtext->qdone = 0;
   cc = cap * sizeof(ch *);
   qtext->qtext = (ch **) zmalloc(cc,"qtext");
   memset(qtext->qtext,0,cc);
   return;
}


//  add new text string to Qtext queue
//  if queue full, sleep until space is available

void Qtext_put(Qtext *qtext, ch *format, ...)
{
   int      qnext;
   va_list  arglist;
   ch       message[200];

   va_start(arglist,format);
   vsnprintf(message,199,format,arglist);
   va_end(arglist);

   qnext = qtext->qnewest + 1;
   if (qnext == qtext->qcap) qnext = 0;
   while (qtext->qtext[qnext]) zsleep(0.01);
   qtext->qtext[qnext] = zstrdup(message,"Qtext");
   qtext->qnewest = qnext;
   return;
}


//  remove oldest text string from Qtext queue
//  if queue empty, return a null string
//  returned string is subject for zfree()

ch * Qtext_get(Qtext *qtext)
{
   int      qnext;
   ch       *text;

   if (qtext->qcap == 0) return 0;
   qnext = qtext->qoldest + 1;
   if (qnext == qtext->qcap) qnext = 0;
   text = qtext->qtext[qnext];
   if (! text) return 0;
   qtext->qtext[qnext] = 0;
   qtext->qoldest = qnext;
   return text;
}


//  close Qtext, zfree() any leftover strings

void Qtext_close(Qtext *qtext)
{
   for (int ii = 0; ii < qtext->qcap; ii++)
      if (qtext->qtext[ii]) zfree(qtext->qtext[ii]);
   zfree(qtext->qtext);
   qtext->qcap = 0;
   return;
}


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

//  compute variance for a list of numbers
//  std. deviation = sqrtf(variance) 

float variance(float *vals, int N)                                               //  24.60
{
   float    mean1, mean2, variance;
   int      ii;
   
   if (N == 0) return 0;

   mean1 = mean2 = 0;
      
   for (ii = 0; ii < N; ii++)
   {
      mean1 += vals[ii];
      mean2 += vals[ii] * vals[ii];
   }
   
   mean1 = mean1 / N;
   mean2 = mean2 / N;
   
   variance = fabsf(mean2 - mean1 * mean1);
   return variance;
}


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

   Initialize application files according to following conventions:              //  new version
     + binary executable is at:  /prefix/bin/appname                             //  = PREFIX/bin/appname
     + other application folders are derived as follows:
         /prefix/share/appname/data/            desktop, parameters, userguide  ...
         /prefix/share/doc/appname/             README, changelog, appname.man ...
         /prefix/share/appname/icons/           application icon files, filename.png
         /prefix/share/appname/images/          application image files
         /home/user/.appname/                   some installation files are copied here
         /home/user/.appname/appname-N.N.log    log file with error messages

   zprefix        install location              /usr or /usr/local
   zdatadir       installed data files          /prefix/share/appname/data/
   zimagedir      installed image files         /prefix/share/appname/images/
   zdocdir        documentation files           /prefix/share/doc/appname/
   zhomedir       local app files               /home/<user>/.appname/

   If it does not already exist, an application folder for the current user is
   created at /home/username/.appname (following common Linux convention).
   If this folder was created for the first time, copy specified files
   (following the 1st argument) from the install folder into the newly created
   user-specific folder. The assumption is that all initial data files for the
   application (e.g. parameters) will be in the install data folder, and these are
   copied to the user folder where the user or application can modify them.

   If the running program is not connected to a terminal device, stdout and stderr are
   redirected to the log file at /home/user/.appname/appname-N.N.log

***/

ch * get_zprefix() { return zfuncs::zprefix; }                                   //  /usr or /usr/local
ch * get_zhomedir() { return zfuncs::zhomedir; }                                 //  /home/<user>/.appname
ch * get_zdatadir() { return zfuncs::zdatadir; }                                 //  data files
ch * get_zdocdir()  { return zfuncs::zdocdir;  }                                 //  documentation files
ch * get_zimagedir()  { return zfuncs::zimagedir;  }                             //  image files


int zinitapp(ch *appvers, int argc, ch *argv[])                                  //  appname-N.N
{
   ch          buff[300];
   ch          LNhomedir[200];
   ch          username[140];
   ch          cssfile[200];
   ch          *pp, *ch_time;
   int         ii, cc, err;
   time_t      startime;
   STATB       statB;
   FILE        *fid;

   pp = getenv("HOME");                                                          //  24.50
   if (pp) err = chdir(pp);
   Plog(0,"working directory: %s \n",pp);

   startime = time(null);                                                        //  app start time, secs. since 1970

   catch_signals();                                                              //  catch signals, do backtrace

   Plog(1,"command: ");
   for (ii = 0; ii < argc; ii++) Plog(1,"%s ",argv[ii]);                         //  log command line
   Plog(1,"\n");

   setlocale(LC_NUMERIC,"C");                                                    //  stop comma decimal points

   setpgid(0,0);                                                                 //  make a new process group

   strncpy0(zappvers,appvers,40);                                                //  appname-N.N
   Plog(1,"%s \n",zappvers);

   strncpy0(zappname,appvers,40);                                                //  appname   without version
   pp = strchr(zappname,'-');
   if (pp && pp[1] > '9') pp = strchr(pp+1,'-');                                 //  bypass '-' in appname
   if (pp) *pp = 0;

   if (argc > 1 && strmatchV(argv[1],"-ver","-v",0)) exit(0);                    //  exit if nothing else wanted

   progexe = 0;
   cc = readlink("/proc/self/exe",buff,300);                                     //  get my executable program path
   if (cc <= 0) zexit(1,"readlink() /proc/self/exe) failed");
   buff[cc] = 0;                                                                 //  readlink() quirk
   progexe = zstrdup(buff,"zinitapp");

   Plog(1,"program exe: %s \n",progexe);                                         //  executable path

   strncpy0(zprefix,progexe,200);
   pp = strstr(zprefix,"/bin/");                                                 //  get install prefix (e.g. /usr)
   if (pp) *pp = 0;
   else (strcpy(zprefix,"/usr"));                                                //  if /xxxxx/bin --> /xxxxx

   strncatv(zdatadir,199,zprefix,"/share/",zappname,"/data",null);               //  /prefix/share/appname/data
   strncatv(zimagedir,199,zprefix,"/share/",zappname,"/images",null);            //  /prefix/share/appname/images
   strncatv(zdocdir,199,zprefix,"/share/doc/",zappname,null);                    //  /prefix/share/doc/appname

   ch_time = zstrdup(build_date_time,"zinitapp");
   if (ch_time[4] == ' ') ch_time[4] = '0';                                      //  replace month day ' d' with '0d'
   Plog(1,"build date/time: %s \n",ch_time);

   strncpy0(username,getenv("USER"),140);                                        //  get user name
   if (strlen(username) > 138) zexit(1,"username too big");                      //  insure derived folders <200 ch.

   *zhomedir = 0;                                                                //  app home dir

   if (argc > 2 && strmatch(argv[1],"-home") && *argv[2] == '/')                 //  get appname home folder from caller
      strncpy0(zhomedir,argv[2],200);                                            //  (any user-owned folder) 
   
   if (! *zhomedir) {
      snprintf(LNhomedir,200,"%s/.%s-home",getenv("HOME"),zappname);             //  check $HOME/.appname-home             24.20
      fid = fopen(LNhomedir,"r");
      if (fid) {
         pp = fgets_trim(LNhomedir,200,fid);                                     //  if found, read pointer to home folder
         if (pp) strncpy0(zhomedir,pp,200);                                      //  (any user-owned folder)
         fclose(fid);
      }
   }
   
   if (! *zhomedir) 
      snprintf(zhomedir,200,"%s/.%s",getenv("HOME"),zappname);                   //  use $HOME/.appname/                   24.20
      
   Plog(0,"%s home folder: %s \n",zappname,zhomedir);

   if (strchr(zhomedir,' ')) zexit(1,"home folder name contains a space");       //  forbid space or quote in home folder
   if (strchr(zhomedir,'"')) zexit(1,"home folder name contains a quote");
   if (strchr(zhomedir,'\'')) zexit(1,"home folder name contains a quote");

   err = stat(zhomedir,&statB);                                                  //  home folder exists already?
   if (err) {
      err = mkdir(zhomedir,0750);                                                //  no, create
      if (err) zexit(1,"cannot create %s: \n %s",zhomedir,strerror(errno));
   }

   if (! isatty(fileno(stdin)))                                                  //  not attached to a terminal
   {
      snprintf(logfile,199,"%s/%s.log",zhomedir,zappvers);                       //  /home/<user>/appname-N.N.log
      remove(logfile);                                                           //  remove prior
      fid = freopen(logfile,"a",stdout);                                         //  redirect stdout/stderr to log file
      fid = freopen(logfile,"a",stderr);
      if (! fid) Plog(0,"*** cannot redirect stdout and stderr \n");
      Plog(0,"log file: %s \n",logfile);
   }

   Plog(1,"-------------------------------------------\n");                      //  log file separator

   ch_time = ctime(&startime);                                                   //  start time: Ddd Mmm dd hh:mm:ss.nn
   ch_time[19] = 0;                                                              //  eliminate hundredths of seconds
   if (ch_time[8] == ' ') ch_time[8] = '0';                                      //  replace ' d' with '0d'
   Plog(1,"start %s %s \n",zappname,ch_time);
   fflush(0);

   tid_main = pthread_self();                                                    //  thread ID of main() process

   err = stat(zdatadir,&statB);                                                  //  files from .../appname/data
   if (! err) zshell("noerr","cp -R -n %s/* %s 2>/dev/null",zdatadir,zhomedir);  //    --> user app home (no replace)      24.20
                                                                                 //  new: -n triggers error status         24.20
   //  GTK initialization

   setenv("GDK_BACKEND","x11",0);                                                //  needed by Fedora (11/2023) but not Ubuntu
   setenv("GTK_THEME","default",0);                                              //    " "

   if (gtk_clutter_init(&argc,&argv) != CLUTTER_INIT_SUCCESS)                    //  intiz. clutter and GTK
      zexit(1,"gtk_clutter_init() failed");

   if (! gtk_init_check(0,null))
      zexit(1,"gtk_init_check() failed");

   setlocale(LC_NUMERIC,"C");                                                    //  NECESSARY: GTK changes locale

   int v1 = gtk_get_major_version();                                             //  get GTK release version
   int v2 = gtk_get_minor_version();
   int v3 = gtk_get_micro_version();
   Plog(1,"GTK version: %d.%02d.%02d \n",v1,v2,v3);

   display = gdk_display_get_default();                                          //  get hardware info
   screen = gdk_screen_get_default();

   GdkRectangle   rect;
   GdkMonitor     *monitor;

   monitor = gdk_display_get_primary_monitor(display);
   gdk_monitor_get_geometry(monitor,&rect);
   monitor_ww = rect.width;
   monitor_hh = rect.height;

   if (! monitor_ww) zexit(1,"GTK cannot get monitor data");

   GdkSeat    *gdkseat = 0;                                                      //  screen / KB / pointer associations
   if (screen) gdkseat = gdk_display_get_default_seat(display);                  //  Ubuntu 16.10
   if (screen) gtksettings = gtk_settings_get_for_screen(screen);
   if (gdkseat) mouse = gdk_seat_get_pointer(gdkseat);

   if (! mouse) zexit(1,"GTK cannot get pointer device");

   if (gtksettings) {                                                            //  get default font
      g_object_get(gtksettings,"gtk_font_name",&appfont,null);
      zsetfont(appfont);                                                         //  set mono and bold versions
   }

   //  widget style changes if widgets.css file is present
   
   snprintf(cssfile,200,"%s/widgets.css",get_zhomedir());
   err = stat(cssfile,&statB);                                                   //  24.10
   if (! err) {
      GtkStyleProvider *provider = (GtkStyleProvider *) gtk_css_provider_new();
      gtk_style_context_add_provider_for_screen(zfuncs::screen,provider,999);
      gtk_css_provider_load_from_path(GTK_CSS_PROVIDER(provider),cssfile,0);
   }

   return 1;
}


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

//  popup window with application 'about' information

void zabout(GtkWidget *parent)
{
   int zabout_dialog_event(zdialog *zd, ch *event);

   zdialog  *zd;
   int      cc;
   ch       installed_release[80];
   ch       title[40];
   ch       *execfile;

/***
    __________________________________________________
   |               About Appname                      |
   |                                                  |
   |  installed release: appname-N.N  Mon dd yyyy     |                          //  'query release' removed
   |  executable: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx       |
   |  contact: mkornelix@gmail.com                    |
   |__________________________________________________|

***/

   execfile = progexe;

   snprintf(installed_release,80,"%s  %s",zappvers,build_date_time);             //  appname-N.N  Mon dd yyyy hh:mm:ss

   cc = strlen(installed_release);
   installed_release[cc-9] = 0;                                                  //  remove hh:mm:ss
   if (installed_release[cc-16] == ' ') installed_release[cc-16] = '0';          //  replace "Jan  1" with "Jan 01"

   snprintf(title,40,"About %s",zappname);
   zd = zdialog_new(title,parent,null);

   zdialog_add_widget(zd,"hbox","hbirel","dialog");
   zdialog_add_widget(zd,"label","labir1","hbirel","installed release:","space=3");
   zdialog_add_widget(zd,"label","labir2","hbirel",installed_release);

   zdialog_add_widget(zd,"hbox","hbexe","dialog");
   zdialog_add_widget(zd,"label","labexe1","hbexe","executable:","space=3");
   zdialog_add_widget(zd,"label","labexe2","hbexe",execfile);

   zdialog_add_widget(zd,"hbox","hbcontact","dialog");
   zdialog_add_widget(zd,"label","labcontact","hbcontact","contact:","space=3");
   zdialog_add_widget(zd,"label","contact","hbcontact",zcontact);

   zdialog_run(zd,zabout_dialog_event,"parent");
   return;
}


//  dialog event and completion function

int zabout_dialog_event(zdialog *zd, ch *event)
{
   if (zd->zstat) zdialog_free(zd);
   return 1;
}


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

//  set a new application font via GtkSettings
//  newfont should be something like "sans 11"
//  use generic monospace font since app font may not have a mono version

void zsetfont(ch *newfont)
{
   ch       font[40], bfont[48], mfont[48], mbfont[56];
   ch       junk[40];
   int      nn, size;

   if (! gtksettings) return;

   nn = sscanf(newfont,"%s %d",font,&size);                                      //  "sans 11"
   if (nn != 2) {
      nn = sscanf(newfont,"%s %s %d",font,junk,&size);
      if (nn != 3) goto fail;
   }
   if (size < 5 || size > 30) goto fail;

   g_object_set(gtksettings,"gtk-font-name",newfont,null);                       //  set dialog font

   snprintf(bfont,48,"%s bold %d",font,size);                                    //  "sans bold 11"
   snprintf(mfont,48,"mono %d",size-1);                                          //  "mono 10"
   snprintf(mbfont,56,"mono bold %d",size-1);                                    //  "mono bold 10"
   appfont = zstrdup(newfont,"zsetfont");
   appboldfont = zstrdup(bfont,"zsetfont");
   appmonofont = zstrdup(mfont,"zsetfont");
   appmonoboldfont = zstrdup(mbfont,"zsetfont");
   appfontsize = size;
   return;

fail:
   Plog(0,"cannot set font: %s \n",newfont);
   return;
}


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

//  get the font character width and height for a given widget
//  returns 0 if OK, +N if error

int widget_font_metrics(GtkWidget *widget, int &fontwidth, int &fontheight)
{
   PangoContext         *pangocontext;
   PangoFontDescription *pangofontdesc;
   PangoFontMetrics     *pangofontmetrics;
   PangoLanguage        *pangolanguage;

   pangocontext = gtk_widget_get_pango_context(widget);
   pangofontdesc = pango_context_get_font_description(pangocontext);
   pangolanguage = pango_language_get_default();
   pangofontmetrics = pango_context_get_metrics(pangocontext,pangofontdesc,pangolanguage);
   if (! pangofontmetrics) {
      Plog(0,"widget_font_metrics() failed \n");
      return 1;
   }

   fontwidth = pango_font_metrics_get_approximate_char_width(pangofontmetrics);
   fontheight = pango_font_metrics_get_ascent(pangofontmetrics)
              + pango_font_metrics_get_descent(pangofontmetrics);
   fontwidth /= PANGO_SCALE;
   fontheight /= PANGO_SCALE;

   return 0;
}


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

//  Find installation file or user file.
//    file type: doc, data, user
//    file name: README, changelog, userguide, parameters ...
//  Returns complete file name, e.g. /usr/share/appname/data/userguide
//  Output filespec should be 200 bytes (limit for all installation files).
//  Returns 0 if OK, +N if not found.

int get_zfilespec(ch *filetype, ch *filename, ch *filespec)
{
   int      cc, err;
   STATB    statB;

   filespec[0] = '/';
   strcat(filespec,filetype);                                                    //  leave /type as default

   if (strmatch(filetype,"doc")) strcpy(filespec,zdocdir);                       //  /usr/share/doc/appname
   if (strmatch(filetype,"data")) strcpy(filespec,zdatadir);                     //  /usr/share/appname/data
   if (strmatch(filetype,"user")) strcpy(filespec,zhomedir);                     //  /home/<user>/.appname

   cc = strlen(filespec);
   filespec[cc] = '/';                                                           //  /folders.../
   strcpy(filespec+cc+1,filename);                                               //  /folders.../filename
   err = stat(filespec,&statB);
   if (! err) return 0;                                                          //  found

   if (! strmatch(filetype,"doc")) return 1;                                     //  doc files may be in
   strcpy(filespec,zdocdir);                                                     //    /usr/share/doc/appname/extras
   strcat(filespec,"/extras/");                                                  //       due to Linux chaos
   cc = strlen(filespec);
   strcpy(filespec+cc,filename);
   err = stat(filespec,&statB);
   if (! err) return 0;                                                          //  found

   return 1;                                                                     //  not found
}


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

//  display application log file in a popup window
//  The log file is /home/<user>/.appname/logfile

void showz_logfile(GtkWidget *parent)
{
   ch   buff[200];

   fflush(0);
   snprintf(buff,199,"cat %s",logfile);
   popup_command(buff,800,600,parent);
   return;
}


//  find and show a text file in /usr/share/doc/appname/
//                            or /usr/share/appname/data
//  the text file may also be a compressed .gz file
//  type is "doc" or "data"

void showz_textfile(ch *type, ch *file, GtkWidget *parent)
{
   ch       filex[40], filespec[200], command[200];
   int      err;

   strncpy0(filex,file,36);                                                      //  look for gzip file first
   strcat(filex,".gz");

   err = get_zfilespec(type,filex,filespec);
   if (! err) {
      snprintf(command,200,"zcat \"%s\"",filespec);                              //  use quotes around filename
      popup_command(command,700,500,parent,1);
      return;
   }

   strncpy0(filex,file,35);                                                      //  look also for bzip2 file
   strcat(filex,".bz2");

   err = get_zfilespec(type,filex,filespec);
   if (! err) {
      snprintf(command,200,"bzcat \"%s\"",filespec);
      popup_command(command,700,500,parent,1);
      return;
   }

   strncpy0(filex,file,36);                                                      //  look for uncompressed file

   err = get_zfilespec(type,filex,filespec);
   if (! err) {
      snprintf(command,200,"cat \"%s\"",filespec);
      popup_command(command,700,500,parent,1);
      return;
   }

   zmessageACK(mainwin,"file not found: %s %s",type,file);
   return;
}


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

   void showz_docfile(GtkWidget *parent, ch *docfile, ch *topic)

   Show docfile in popup scrolling text window with 'topic' at the top.
   docfile is located in data folder: get_zdatadir()
   images are located in image folder: get_zimagedir()

   docfile format:

   TOPIC: TOPIC 1                                                                topic: bold
   text text text text text text text text text text text text ...               topic text

   TOPIC: TOPIC 2
   +image: file1.png  +image: file2.jpg                                          embedded images

   text text text text text text text text {TOPIC 1} text text ...               link to topic, bold

   ^bold subtopic line^                                                          subtopic, bold                            24.10
   text text text text text ^bold text bold text^ text text ...                  embedded bold text

   text text text text text  ^http.........^  text text text ...                 web link, bold                            24.10

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

namespace showz_docfile_names
{
   #define TMAX 1000                                                             //  max. topics and markups
   zdialog     *zd = 0;
   GtkWidget   *textwidget;
   int         cc, ii, jj;
   int         currline;
   ch          *pp;
   ch          *Tname[TMAX];                                                     //  all topic names (link targets)
   int         Tline[TMAX];                                                      //  topic lines
   int         Bline[TMAX], Bpos[TMAX], Bcc[TMAX];                               //  bold texts: line, posn, cc
   int         TN, BN, BF;                                                       //  counts, flags
   zlist_t     *RTopics = 0;                                                     //  recent topics list
   ch          RTfile[200] = "";                                                 //  recent topics file
   int         RTmax = 20;                                                       //  max. recent topics
}


void showz_docfile(GtkWidget *parent, ch *docfile, ch *utopic)
{
   using namespace showz_docfile_names;

   void showz_docfile_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void audit_docfile(ch *docfile);

   FILE        *fid;
   ch          filespec[200], buff1[10000], buff2[10000];                        //  record cc limit (100 lines x 100 char.)
   ch          topic[50], image[100];                                            //  limits: topic name, image name
   ch          *pp1, *pp2;
   int         Fm, line, pos1, pos2, cc;
   GdkPixbuf   *pixbuf;
   GError      *gerror;

   if (utopic && strmatch(utopic,"quit")) {                                      //  quit - save recent topics list
      if (RTopics && *RTfile) zlist_to_file(RTopics,RTfile);
      if (zdialog_valid2(zd)) popup_report_close(zd,0);                          //  close open report or UG
      return;
   }

   if (utopic && strmatch(utopic,"validate")) {                                  //  check document for errors
      audit_docfile(docfile);                                                    //  (developer tool)
      return;
   }

   if (zd && zdialog_valid2(zd,docfile))                                         //  document active already
      goto initz_done;

   snprintf(RTfile,200,"%s/recent_topics",get_zhomedir());                       //  get recent topics list
   RTopics = zlist_from_file(RTfile);
   if (! RTopics) RTopics = zlist_new(0);

   for (ii = 0; ii < TN; ii++) zfree(Tname[ii]);                                 //  free prior docfile data if any

   TN = BN = 0;

   snprintf(filespec,200,"%s/%s",get_zdatadir(),docfile);                        //  open docfile
   fid = fopen(filespec,"r");
   if (! fid) zexit(1,"%s %s \n",filespec,strerror(errno));

   for (line = 0; ; line++)                                                      //  loop docfile recs/lines
   {
      pp1 = fgets_trim(buff1,10000,fid);                                         //  line with null at end
      if (! pp1) break;                                                          //  EOF
      if (strmatchN(pp1,"EOF",3)) break;                                         //  end of displayed text

      if (! strmatchN(buff1,"TOPIC:",6)) continue;                               //  not a topic name
      pp1 = buff1 + 6;
      while (*pp1 == ' ') pp1++;
      pp2 = pp1 + strlen(pp1);
      while (*pp2 <= ' ') pp2--;
      cc = pp2 - pp1 + 1;
      if (cc < 1 || cc > 49) continue;
      strncpy0(topic,pp1,cc+1);                                                  //  add topic and line number to topic list
      Tname[TN] = zstrdup(topic,"docfile");
      Tline[TN] = line;
      if (++TN == TMAX) zexit(1,"docfile exceeds %d topics \n",TMAX);
   }

   fclose(fid);

   Plog(1,"Docfile topics: %d \n",TN);

   zd = popup_report_open(docfile,parent,900,800,1,0,showz_docfile_clickfunc,    //  popup window for docfile text display
                      "Recent", "<", ">", "Find", "Save", "X", 0);               //    + buttons
   if (! zd) zexit(1,"cannot open docfile window \n");

   popup_report_font_attributes(zd);                                             //  use high contrast font
   textwidget = zdialog_gtkwidget(zd,"text");                                    //  text widget in zdialog

   snprintf(filespec,200,"%s/%s",get_zdatadir(),docfile);                        //  open docfile again
   fid = fopen(filespec,"r");
   if (! fid) zexit(1,"%s %s \n",filespec,strerror(errno));

   for (line = 0; ; line++)                                                      //  loop docfile recs/lines
   {
      pp1 = fgets_trim(buff1,10000,fid);                                         //  line with null at end
      if (! pp1) break;                                                          //  EOF
      if (strmatchN(pp1,"EOF",3)) break;                                         //  end of displayed text

      if (strmatchN(buff1,"TOPIC:",6))                                           //  TOPIC: TOPIC NAME
      {
         pp1 = buff1 + 6;
         while (*pp1 == ' ') pp1++;
         popup_report_write(zd,1,"%s \n",pp1);                                   //  output TOPIC NAME, bold
         continue;
      }

      pp1 = strstr(buff1,"+image:");                                             //  line has image names
      if (pp1) {
         while (pp1) {
            pp1 += 7;
            while (*pp1 == ' ') pp1++;                                           //  remove blanks
            strncpy0(image,pp1,100);
            pp2 = strchr(image,' ');
            if (pp2) *pp2 = 0;
            snprintf(filespec,200,"%s/%s",get_zimagedir(),image);                //  full filespec
            gerror = 0;
            pixbuf = gdk_pixbuf_new_from_file(filespec,&gerror);                 //  convert to pixbuf image
            if (pixbuf) {
               popup_report_write(zd,0,"  ",0);                                  //  leading spaces
               popup_report_insert_pixbuf(zd,line,pixbuf);                       //  write image to output line
               g_object_unref(pixbuf);
            }
            else Plog(0,"cannot load image file: %s \n",image);
            pp1 = strstr(pp1,"+image:");                                         //  next image file
         }
         popup_report_write(zd,0,"\n",0);                                        //  write image line EOL
         continue;                                                               //  next input line
      }

      strncpy0(buff2,buff1,10000);                                               //  line is text
      Fm = 0;                                                                    //  buff1: line with bold markups

      for (pp1 = buff2; (pp1 = strpbrk(pp1,"{}^"));) {                           //  buff2: line without markups           24.10
         cc = strlen(pp1+1);
         memmove(pp1,pp1+1,cc+1);
         Fm++;                                                                   //  markups found in this line
      }

      popup_report_write(zd,0,"%s \n",buff2);                                    //  write line to output, no markups

      if (! Fm) continue;                                                        //  no markups found, done

      BF = 0;                                                                    //  intiz. no markups active

      pos1 = pos2 = 0;                                                           //  char. posn. with/without markups

      while (buff1[pos1])                                                        //  loop chars. in line
      {
         if (! strchr("{}^",buff1[pos1])) {                                      //  not a markup char.                    24.10
            if (BF) ++Bcc[BN];                                                   //  count cc for active markups
            pos1++; pos2++;
            continue;
         }

         if (buff1[pos1] == '{') {                                               //  ... {bold text} ... link to topic
            if (BN == TMAX) zexit(1,"docfile > %d markups \n",TMAX);
            BF = 1;                                                              //  start bold text
            Bline[BN] = line;
            Bpos[BN] = pos2;
            Bcc[BN] = 0;
         }

         else if (buff1[pos1] == '}') {                                          //  end bold text
            BF = 0;
            BN++;                                                                //  bold markup count
         }

         else if (buff1[pos1] == '^') {                                          //  ... ^bold text^ ...                   24.10
            if (! BF) {                                                          //  starting ^
              BF = 1;
              Bline[BN] = line;
              Bpos[BN] = pos2;
              Bcc[BN] = 0;
            }
            else {                                                               //  ending ^
               BF = 0;
               BN++;
            }
         }

         pos1++;                                                                 //  skip over markup char.
      }

      if (BF) BN++;                                                              //  EOL without trailing } or ^
   }                                                                             //  end loop line

   fclose(fid);

   for (ii = 0; ii < BN; ii++)                                                   //  do all text bolds
      popup_report_bold_word(zd,Bline[ii],Bpos[ii],Bcc[ii]);

   zmainloop();                                                                  //  necessary here for some reason

initz_done:

   currline = 0;                                                                 //  docfile line for topic

   if (utopic)                                                                   //  initial topic from caller
   {
      strncpy0(topic,utopic,50);
      cc = strlen(topic);

      for (ii = 0; ii < TN; ii++) {                                              //  search docfile topics
         if (strmatchcase(topic,Tname[ii])) {
            currline = Tline[ii];                                                //  get line of matching topic
            break;
         }
      }

      if (ii == TN)
         Plog(0,"topic not found: %s %s \n",utopic,topic);
      else {
         zlist_prepend(RTopics,topic,0);                                         //  add to recent topics, 1st position
         ii = zlist_find(RTopics,topic,1);
         if (ii > 0) zlist_remove(RTopics,ii);                                   //  if topic present later, remove it
         ii = zlist_count(RTopics);
         if (ii > RTmax) zlist_remove(RTopics,ii-1);                             //  limit entry count
      }
   }

   popup_report_scroll_top(zd,currline);                                         //  scroll to topic line

   return;
}


//  handle clicks on document window and KB inputs

void showz_docfile_clickfunc(GtkWidget *textwidget, int line, int posn, int kbkey)
{
   using namespace showz_docfile_names;

   int         ii, jj, cc;
   int         vtop, vbott, page, posn8;
   ch          *text, *pp1, *pp2;
   ch          *topic;
   ch          text2[10000], weblink[200];
   static int  Ltab[10], maxL = 10, Lpos = 0;                                    //  last 10 links clicked

   gtk_widget_grab_focus(textwidget);                                            //  necessary for some reason

   textwidget_get_visible_lines(textwidget,vtop,vbott);                          //  range of lines on screen

   if (kbkey == 'r' || kbkey == 'R')                                             //  key 'R', recent topics
   {
      topic = popup_picklist(textwidget,(ch **) RTopics->mber,0,                 //  choose a topic
                                                   RTopics->count);
      if (! topic) return;

      for (ii = 0; ii < TN; ii++)                                                //  search docfile topics
         if (strmatchcase(topic,Tname[ii])) break;
      if (ii == TN) return;                                                      //  not found

      currline = Tline[ii];                                                      //  get line of matching topic
      popup_report_scroll_top(zd,currline);                                      //  scroll to topic line

      zlist_prepend(RTopics,topic,0);                                            //  add to recent topics, 1st position
      ii = zlist_find(RTopics,topic,1);
      if (ii > 0) zlist_remove(RTopics,ii);                                      //  if topic present later, remove it
      ii = zlist_count(RTopics);
      if (ii > RTmax) zlist_remove(RTopics,ii-1);                                //  limit entry count
      return;
   }

   if (kbkey == GDK_KEY_Left || kbkey == '<') {                                  //  left arrow, go back
      Ltab[Lpos] = currline;
      if (Lpos > 0) Lpos--;
      currline = Ltab[Lpos];
      textwidget_scroll_top(textwidget,currline);                                //  scroll line to top of window
      return;
   }

   if (kbkey == GDK_KEY_Right || kbkey == '>') {                                 //  right arrow, go forward
      Ltab[Lpos] = currline;
      if (Lpos < maxL-1 && Ltab[Lpos+1] >= 0)
         currline = Ltab[++Lpos];
      textwidget_scroll_top(textwidget,currline);                                //  scroll line to top of window
      return;
   }

   if (kbkey == GDK_KEY_F || kbkey == GDK_KEY_f) {                               //  key 'F' same as [find] button
      zdialog_send_event(zd,"Find");
      return;
   }

   if (kbkey >= 0xfd00) {                                                        //  navigation key
      page = vbott - vtop - 2;                                                   //  page size, lines
      if (page < 0) page = 0;
      currline = 0;                                                              //  default
      if (kbkey == GDK_KEY_Up) currline = vtop - 1;                              //  handle some navigation keys
      else if (kbkey == GDK_KEY_Down) currline = vbott + 1;
      else if (kbkey == GDK_KEY_Page_Up) currline = vtop - page;
      else if (kbkey == GDK_KEY_Page_Down) currline = vbott + page;
      else if (kbkey == GDK_KEY_KP_Page_Up) currline = vtop - page;
      else if (kbkey == GDK_KEY_KP_Page_Down) currline = vbott + page;
      else if (kbkey == GDK_KEY_KP_9) currline = vtop - page;
      else if (kbkey == GDK_KEY_KP_3) currline = vbott + page;
      else if (kbkey == GDK_KEY_Home) currline = 0;
      else if (kbkey == GDK_KEY_End) currline = 999999;
      if (currline < 0) currline = 0;
      textwidget_scroll(textwidget,currline);                                    //  put line on screen
      return;
   }

   if (line < 0 || posn < 0) return;                                             //  clicked line and position

   text = textwidget_line(textwidget,line,1);                                    //  get line text
   if (! text) return;

   strncpy0(text2,text,posn+1);                                                  //  compensate utf8 chars. before posn
   posn8 = posn + strlen(text2) - utf8len(text2);

   for (ii = 0; ii < BN; ii++) {                                                 //  is clicked text bolded text
      if (line == Bline[ii]) {
         if (posn8 >= Bpos[ii] && posn8 <= Bpos[ii] + Bcc[ii]) {                 //  yes
            for (jj = 0; jj < TN; jj++)
               if (strmatchN(Tname[jj],text+Bpos[ii],Bcc[ii])) break;            //  does it match a topic name
            if (jj < TN) goto topiclink;                                         //  yes
         }
      }
   }
   goto weblink;

topiclink:
   topic = Tname[jj];                                                            //  clicked topic
   currline = Tline[jj];
   textwidget_scroll_top(textwidget,currline);                                   //  scroll topic to top of window

   zlist_prepend(RTopics,topic,0);                                               //  add to recent topics, 1st position
   ii = zlist_find(RTopics,topic,1);
   if (ii > 0) zlist_remove(RTopics,ii);                                         //  if topic present later, remove it
   ii = zlist_count(RTopics);
   if (ii > RTmax) zlist_remove(RTopics,ii-1);                                   //  limit entry count

   if (Lpos == maxL-1) {
      for (jj = 0; jj < maxL-1; jj++)                                            //  back tab table full,
         Ltab[jj] = Ltab[jj+1];                                                  //    discard oldest
      Lpos--;
   }

   Ltab[Lpos] = vtop;                                                            //  curr. top line >> back tab
   Lpos++;                                                                       //  advance back tab position
   Ltab[Lpos] = currline;                                                        //       >> back tab
   return;

weblink:
   for ( ; posn >= 0; posn--)
      if ( *(text+posn) == ' ') break;                                           //  click position, preceding blank
   if (posn < 0) posn = 0;
   if (text[posn] == ' ') posn += 1;                                             //  eliminate preceding blank
   pp1 = text + posn;
   pp2 = strchr(pp1,' ');                                                        //  following blank or EOL
   if (pp2) cc = pp2 - pp1;
   else cc = strlen(pp1);
   if (pp1[cc-1] == '.') cc--;                                                   //  remove trailing period
   if (cc > 199) return;
   strncpy0(weblink,pp1,cc+1);                                                   //  copy clicked text string
   if (strmatchN(pp1,"http",4))                                                  //  if "http..." assume a web link
      zshell("log ack","xdg-open %s",weblink);
   return;
}


//  validate the F1_help_topic links and the internal links in a docfile
//  (developer tool)

void audit_docfile(ch *docfile)
{
   #define LMAX 10000                                                            //  max. docfile lines/recs
   ch          *textlines[LMAX];
   ch          *Tname[TMAX];
   ch          filespec[200], buff[10000], image[100];                           //  limits: filename, rec. cc, image name
   ch          topic[50];
   ch          *pp1, *pp2, *pp3;
   FILE        *fid;
   int         Ntext, Ntop, Nerrs;
   int         ii, cc, line;
   GdkPixbuf   *pixbuf;
   GError      *gerror;

   Plog(0,"\n*** audit docfile %s *** \n",docfile);

   Ntext = Ntop = Nerrs = 0;

   snprintf(filespec,200,"%s/%s",get_zdatadir(),docfile);                        //  open docfile
   fid = fopen(filespec,"r");
   if (! fid) {
      Plog(0,"%s %s",filespec,strerror(errno));
      return;
   }

   for (line = 0; line < LMAX; line++)                                           //  read docfile text lines
   {
      pp1 = fgets_trim(buff,10000,fid);                                          //  line without \n EOL
      if (! pp1) break;                                                          //  EOF

      textlines[Ntext] = zstrdup(pp1,"docfile");                                 //  copy text line to memory
      if (++Ntext == LMAX) zexit(1,"exceed LMAX text recs");

      if (! strmatchN(pp1,"TOPIC:",6)) continue;                                 //  not a topic line
      pp1 += 6;
      while (*pp1 == ' ') pp1++;
      cc = strlen(pp1);
      if (cc < 2 || cc > 49) continue;
      strncpy0(topic,pp1,cc+1);                                                  //  add topic to list
      Tname[Ntop] = zstrdup(topic,"docfile");
      if (++Ntop == TMAX) zexit(1,"exceed TMAX topics");
      printf("topic: %s \n",topic);
   }

   fclose(fid);

   printf("text lines: %d  topics: %d \n",Ntext,Ntop);

   for (line = 0; line < Ntext; line++)                                          //  process text lines
   {
      pp1 = textlines[line];

      pp2 = strstr(pp1,"+image:");
      if (pp2) {                                                                 //  line contains images
         while (pp2) {
            pp2 += 7;
            while (*pp2 == ' ') pp2++;                                           //  remove blanks
            strncpy0(image,pp2,100);
            pp3 = strchr(image,' ');
            if (pp3) *pp3 = 0;
            snprintf(filespec,200,"%s/%s",get_zimagedir(),image);                //  full filespec
            gerror = 0;
            pixbuf = gdk_pixbuf_new_from_file(filespec,&gerror);                 //  convert to pixbuf image
            if (pixbuf) g_object_unref(pixbuf);
            else {
               Plog(0,"cannot load image file: %s \n",image);
               Nerrs++;
            }
            pp2 = strstr(pp2,"+image:");
         }
         continue;                                                               //  next line
      }

      if (strmatchN(pp1,"TOPIC:",6)) continue;                                   //  skip topic line
      {
         pp1 = strchr(pp1,'{');                                                  //  get topic links in line

         while (pp1)
         {
            pp2 = strchr(pp1+1,'}');                                             //  ... {topic name} ...
            if (! pp2) break;                                                    //      |          |
            pp1 += 1;                                                            //      pp1        pp2
            cc = pp2 - pp1;
            if (cc < 2 || cc > 49) {
               printf("topic >49 chars, line %d: %s \n",line,pp1);               //  topic name > 49 char.
               Nerrs++;
               break;
            }

            strncpy0(topic,pp1,cc+1);
            for (ii = 0; ii < Ntop; ii++)
               if (strcmp(topic,Tname[ii]) == 0) break;
            if (ii == Ntop) {                                                    //  topic not found
               printf("topic not found, line %d: %s \n",line,topic);
               Nerrs++;
            }
            pp1 = strchr(pp2+1,'{');
         }

         continue;                                                               //  next line
      }
   }

   Plog(0," %d errors \n",Nerrs);

   for (ii = 0; ii < Ntext; ii++)                                                //  free memory
      zfree(textlines[ii]);

   for (ii = 0; ii < Ntop; ii++)
      zfree(Tname[ii]);

   return;
}


/********************************************************************************
   GTK utility functions
********************************************************************************/

//  Iterate main loop every "skip" calls.
//  If called within the main() thread, does a GTK main loop to process menu events, etc.
//  You must do this periodically within long-running main() thread tasks if you wish to
//  keep menus, buttons, output windows, etc. alive and working. The skip argument will
//  cause the function to do nothing for skip calls, then perform the normal function.
//  This allows it to be embedded in loops with little execution time penalty.
//  If skip = N, zmainloop() will do nothing for N calls, execute normally, etc.
//  If called from a thread, zmainloop() does nothing.

void zmainloop(int skip)
{
   static int  xskip = 0;

   if (skip && ++xskip < skip) return;
   xskip = 0;

   if (! main_thread()) return;                                                  //  thread caller, do nothing

   while (gtk_events_pending())
      gtk_main_iteration_do(0);

   return;
}


//  Iterate the main loop and sleep for designated time

void zmainsleep(float secs)
{
   while (secs > 0) {
      zmainloop();
      zsleep(0.0001);                                                            //  24.40
      secs = secs - 0.0001;
   }

   return;
}


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

//  cairo drawing context for GDK window

cairo_t * draw_context_create(GdkWindow *gdkwin, draw_context_t &context)
{
   if (context.dcr) {
      Plog(0,"draw_context_create(): nested call");
      return context.dcr;
   }
   context.win = gdkwin;
   context.rect.x = 0;
   context.rect.y = 0;
   context.rect.width = gdk_window_get_width(gdkwin);
   context.rect.height = gdk_window_get_height(gdkwin);
   context.reg = cairo_region_create_rectangle(&context.rect);
   context.ctx = gdk_window_begin_draw_frame(gdkwin,context.reg);
   context.dcr = gdk_drawing_context_get_cairo_context(context.ctx);
   return context.dcr;
}

void draw_context_destroy(draw_context_t &context)
{
   if (! context.dcr) {
      Plog(0,"draw_context_destroy(): not created \n");
      return;
   }
   gdk_window_end_draw_frame(context.win,context.ctx);
   cairo_region_destroy(context.reg);
   /*  cairo_destroy(context.dcr);              this is fatal  */
   context.dcr = 0;
   return;
}


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

//  textwidget functions
//  --------------------
//
//  High-level use of GtkTextView widget for text reports, line editing, text selection
//  In functions below, textwidget = zdialog_gtkwidget(zd,"widgetname"),
//    where "widgetname" is a zdialog "text" widget type.
//  All line numbers and line positions are zero based.


//  clear the text widget to blank

void textwidget_clear(GtkWidget *textwidget)
{
   GtkTextBuffer  *textBuff;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;
   gtk_text_buffer_set_text(textBuff,"",-1);
   return;
}


//  clear the text widget from given line to end

void textwidget_clear(GtkWidget *textwidget, int line)
{
   GtkTextBuffer           *textBuff;
   GtkTextIter             iter1, iter2;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;
   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                       //  iter at line start
   gtk_text_buffer_get_end_iter(textBuff,&iter2);
   gtk_text_buffer_delete(textBuff,&iter1,&iter2);                               //  delete existing line and rest of buffer
   return;
}


//  get the current line count

int textwidget_linecount(GtkWidget *textwidget)
{
   GtkTextBuffer  *textBuff;
   int            nlines;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return 0;
   nlines = gtk_text_buffer_get_line_count(textBuff);
   return nlines;
}


//  append a new line of text to the end of existing text lines
//  line should normally include trailing \n
//  if current last line has no \n, text is appended to this line

void textwidget_append(GtkWidget *textwidget, int bold, ch *format, ...)
{
   va_list        arglist;
   ch             textline[20000];                                               //  textwidget append cc limit
   GtkTextBuffer  *textBuff;
   GtkTextIter    enditer;
   GtkTextTag     *fontag = 0;
   ch             *normfont = zfuncs::appmonofont;
   ch             *boldfont = zfuncs::appmonoboldfont;

   va_start(arglist,format);
   vsnprintf(textline,19999,format,arglist);
   va_end(arglist);

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   gtk_text_buffer_get_end_iter(textBuff,&enditer);                              //  end of text

   if (bold) fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,0);  //  prepare bold/norm tag
   else fontag = gtk_text_buffer_create_tag(textBuff,0,"font",normfont,0);
   gtk_text_buffer_insert_with_tags(textBuff,&enditer,textline,-1,fontag,null);  //  insert line

   return;
}


//  same as above, with scroll to last line added (slower)

void textwidget_append2(GtkWidget *textwidget, int bold, ch *format, ...)
{
   va_list        arglist;
   ch             textline[20000];                                               //  textwidget append cc limit
   GtkTextBuffer  *textBuff;
   GtkTextIter    enditer;
   GtkTextTag     *fontag = 0;
   ch             *normfont = zfuncs::appmonofont;
   ch             *boldfont = zfuncs::appmonoboldfont;
   GtkAdjustment  *vadjust;
   double         upperlimit;

   va_start(arglist,format);
   vsnprintf(textline,19999,format,arglist);
   va_end(arglist);

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   gtk_text_buffer_get_end_iter(textBuff,&enditer);                              //  end of text

   if (bold) fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,0);  //  prepare bold/norm tag
   else fontag = gtk_text_buffer_create_tag(textBuff,0,"font",normfont,0);
   gtk_text_buffer_insert_with_tags(textBuff,&enditer,textline,-1,fontag,null);  //  insert line

   vadjust = gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(textwidget));
   upperlimit = gtk_adjustment_get_upper(vadjust);                               //  does not work within a zdialog FIXME
   gtk_adjustment_set_value(vadjust,upperlimit);

   zmainloop();
   return;
}


//  insert a new line of text after designated line
//  use line -1 to insert before line 0
//  line should normally include trailing \n

void textwidget_insert(GtkWidget *textwidget, int bold, int line, ch *format, ...)
{
   va_list        arglist;
   ch             textline[20000];                                               //  textwidget insert cc limit
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter;
   int            nlines;
   GtkTextTag     *fontag = 0;
   ch             *normfont = zfuncs::appmonofont;
   ch             *boldfont = zfuncs::appmonoboldfont;

   va_start(arglist,format);
   vsnprintf(textline,19999,format,arglist);
   va_end(arglist);

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   if (line < 0) gtk_text_buffer_get_start_iter(textBuff,&iter);                 //  insert before line 0

   if (line >= 0) {
      nlines = gtk_text_buffer_get_line_count(textBuff);                         //  insert after line
      if (line < nlines - 1)
         gtk_text_buffer_get_iter_at_line(textBuff,&iter,line+1);                //  start of next line
      else gtk_text_buffer_get_end_iter(textBuff,&iter);                         //  or end of text
   }

   if (bold) fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,0);  //  prepare bold/norm tag
   else fontag = gtk_text_buffer_create_tag(textBuff,0,"font",normfont,0);
   gtk_text_buffer_insert_with_tags(textBuff,&iter,textline,-1,fontag,null);     //  insert line

   return;
}


//  replace a given line with a new line
//  line = -1: replace last line.  -2: replace last-1 line, etc.
//  new line should normally include trailing \n

void textwidget_replace(GtkWidget *textwidget, int bold, int line, ch *format, ...)
{
   va_list        arglist;
   ch             textline[20000];                                               //  textwidget replace cc limit
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   int            nlines;
   GtkTextTag     *fontag = 0;
   ch             *normfont = zfuncs::appmonofont;
   ch             *boldfont = zfuncs::appmonoboldfont;

   va_start(arglist,format);
   vsnprintf(textline,19999,format,arglist);
   va_end(arglist);

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  lines now in buffer
   if (line < 0) line = nlines + line - 1;
   if (line >= nlines) line = nlines - 1;

   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                       //  line start
   iter2 = iter1;
   gtk_text_iter_forward_line(&iter2);                                           //  end
   gtk_text_buffer_delete(textBuff,&iter1,&iter2);                               //  delete line
   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);

   if (bold) fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,0);  //  prepare bold/norm tag
   else fontag = gtk_text_buffer_create_tag(textBuff,0,"font",normfont,0);
   gtk_text_buffer_insert_with_tags(textBuff,&iter1,textline,-1,fontag,null);    //  insert line

   return;
}


//  delete a given line including the trailing \n

void textwidget_delete(GtkWidget *textwidget, int line)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   int            nlines;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  lines now in buffer
   if (line < 0 || line >= nlines) return;

   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                       //  line start
   iter2 = iter1;
   gtk_text_iter_forward_line(&iter2);                                           //  end
   gtk_text_buffer_delete(textBuff,&iter1,&iter2);                               //  delete line

   return;
}


//  find first line of text containing characters matching input string
//  search is from line1 to end, then from 0 to line1-1
//  returns first matching line or -1 if none
//  comparison is not case sensitive

int textwidget_find(GtkWidget *textwidget, ch *matchtext, int line1, int hilite)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   int            line, nlines, cc;
   ch             *textline = 0, *pp1, *pp2;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return -1;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  lines now in buffer
   if (! nlines) return -1;

   if (line1 < 0) line1 = 0;                                                     //  starting line to search
   if (line1 >= nlines) line1 = 0;
   line = line1;

   while (true)
   {
      gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                    //  line start
      iter2 = iter1;
      gtk_text_iter_forward_line(&iter2);                                        //  end
      textline = gtk_text_buffer_get_text(textBuff,&iter1,&iter2,0);             //  get text
      if (textline) {
         pp1 = strcasestr(textline,matchtext);                                   //  look for matching text
         if (pp1) break;                                                         //  found
         free(textline);
      }
      line++;
      if (line == nlines) line = 0;
      if (line == line1) return -1;                                              //  wrapped around, not found
   }

   if (hilite)
   {
      cc = strlen(matchtext);                                                    //  highlight matching text
      pp2 = pp1 + cc - 1;
      gtk_text_buffer_get_iter_at_line_index(textBuff,&iter1,line,pp1-textline);
      gtk_text_buffer_get_iter_at_line_index(textBuff,&iter2,line,pp2-textline+1);
      gtk_text_buffer_select_range(textBuff,&iter1,&iter2);
   }

   free(textline);
   return line;
}


//  insert a pixbuf image at designated line

void textwidget_insert_pixbuf(GtkWidget *textwidget, int line, GdkPixbuf *pixbuf)
{
   int            nlines;
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  insert after line
   if (line < nlines - 1)
      gtk_text_buffer_get_iter_at_line(textBuff,&iter,line+1);                   //  start of next line
   else gtk_text_buffer_get_end_iter(textBuff,&iter);                            //  or end of text

   gtk_text_buffer_insert_pixbuf(textBuff,&iter,pixbuf);
   return;
}


//  scroll a textwidget to put a given line on screen
//  1st line = 0.  for last line use line = -1.

void textwidget_scroll(GtkWidget *textwidget, int line)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter;
   GtkTextMark    *mark;
   GtkAdjustment  *vadjust;
   double         upperlimit;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   vadjust = gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(textwidget));

   if (line < 0) {                                                               //  bottom
      zmainloop();                                                               //  make it work (GTK problem)
      upperlimit = gtk_adjustment_get_upper(vadjust);
      gtk_adjustment_set_value(vadjust,upperlimit);
   }

   else {
      gtk_text_buffer_get_iter_at_line(textBuff,&iter,line);
      mark = gtk_text_buffer_create_mark(textBuff,0,&iter,0);
      gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(textwidget),mark);
   }

   return;
}


//  scroll a textwidget to put a given line at the top of the window

void textwidget_scroll_top(GtkWidget *textwidget, int line)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter;
   GtkTextMark    *mark;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;
   gtk_text_buffer_get_iter_at_line(textBuff,&iter,line);
   mark = gtk_text_buffer_create_mark(textBuff,0,&iter,0);
   gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(textwidget),mark,0,1,0,0);
   return;
}


//  get the range of textwidget lines currently visible in the window

void textwidget_get_visible_lines(GtkWidget *textwidget, int &vtop, int &vbott)
{
   GdkRectangle   rect;
   GtkTextIter    iter1, iter2;
   int            y1, y2;

   gtk_text_view_get_visible_rect(GTK_TEXT_VIEW(textwidget),&rect);
   y1 = rect.y;
   y2 = y1 + rect.height;
   gtk_text_view_get_line_at_y(GTK_TEXT_VIEW(textwidget), &iter1, y1, 0);
   gtk_text_view_get_line_at_y(GTK_TEXT_VIEW(textwidget), &iter2, y2, 0);
   vtop = gtk_text_iter_get_line(&iter1);
   vbott = gtk_text_iter_get_line(&iter2) - 1;
   return;
}


//  dump the entire textwidget contents into a file

void textwidget_dump(GtkWidget *widget, ch *filename)
{
   FILE        *fid;
   ch          *prec;
   int         line, err;

   fid = fopen(filename,"w");                                                    //  open file
   if (! fid) {
      zmessageACK(mainwin,"cannot open file %s",filename);
      return;
   }

   for (line = 0; ; line++)
   {
      prec = textwidget_line(widget,line,1);                                     //  get text line, strip \n
      if (! prec) break;
      fprintf(fid,"%s\n",prec);                                                  //  output with \n
   }

   err = fclose(fid);                                                            //  close file
   if (err) zmessageACK(mainwin,"file close error");
   return;
}


//  dump the entire textwidget contents into a file, using a save-as dialog

void textwidget_save(GtkWidget *widget, GtkWindow *parent)
{
   ch       *file;

   file = zgetfile("save text to file",parent,"save","noname");
   if (! file) return;
   textwidget_dump(widget,file);
   zfree(file);
   return;
}


//  Get a line of text. Returned text is subject for zfree().
//  trailing \n is included if strip == 0

ch * textwidget_line(GtkWidget *textwidget, int line, int strip)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   int            cc, nlines;
   ch             *textline, *ztext;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return 0;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  lines now in buffer
   if (line < 0 || line >= nlines) return 0;

   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                       //  line start
   iter2 = iter1;
   gtk_text_iter_forward_line(&iter2);                                           //  end
   textline = gtk_text_buffer_get_text(textBuff,&iter1,&iter2,0);                //  get text line
   if (! textline) return 0;
   ztext = zstrdup(textline,"textwidget");
   free(textline);
   if (strip) {
      cc = strlen(ztext);
      if (cc && ztext[cc-1] == '\n') ztext[cc-1] = 0;
   }
   return ztext;
}


//  highlight a given line of text

void textwidget_highlight_line(GtkWidget *textwidget, int line)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   int            nlines;

   zmainloop();

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   nlines = gtk_text_buffer_get_line_count(textBuff);                            //  lines now in buffer
   if (line < 0 || line >= nlines) return;

   gtk_text_buffer_get_iter_at_line(textBuff,&iter1,line);                       //  line start
   iter2 = iter1;
   gtk_text_iter_forward_line(&iter2);                                           //  end
   gtk_text_buffer_select_range(textBuff,&iter1,&iter2);                         //  highlight
   return;
}


//  get the word at the given position within the line
//  words are defined by line starts and ends, and the given delimiters
//  returns word and delimiter (&end)

ch * textwidget_word(GtkWidget *textwidget, int line, int posn, ch *dlims, ch &end)
{
   GtkTextBuffer  *textBuff;
   ch             *txline, *pp1, *pp2, *ztext;
   int            cc, nn;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return 0;

   txline = textwidget_line(textwidget,line,0);
   if (! txline) return 0;

   cc = strlen(txline);
   if (txline[cc-1] == '\n') {
      txline[cc-1] = 0;
      cc--;
   }

   pp1 = pp2 = txline;                                                           //  fix for utf8
   while (true) {
      while (*pp1 == ' ' || strchr(dlims,*pp1)) pp1++;                           //  pp1 = start of next word in line
      if (*pp1 == 0) return 0;
      pp2 = pp1;
      while (true) {
         if (*pp2 == 0) break;
         nn = utf8_position(pp2,1);                                              //  pp2 = next delimiter or EOL
         if (nn < 0) break;
         if (strchr(dlims,pp2[nn])) break;
         pp2 += nn;
         posn += nn-1;
         if (pp2 - txline >= cc) break;
      }
      if (txline+posn >= pp1 && txline+posn <= pp2) break;                       //  pp1-pp2 is word clicked
      nn = utf8_position(pp2,1);
      if (nn < 0) return 0;
      pp1 = pp2 + nn;
      posn += nn-1;
      if (posn >= cc) return 0;
      if (pp1 >= txline+posn) return 0;
   }

   nn = utf8_position(pp2,1);
   if (nn > 0) cc = pp2 - pp1 + nn;
   else cc = pp2 - pp1 + strlen(pp2);
   end = pp1[cc];

   ztext = (ch *) zmalloc(cc+1,"textwidget");
   strncpy0(ztext,pp1,cc+1);
   zfree(txline);
   return ztext;
}


//  highlight text at line and positiion, length cc

void textwidget_highlight_word(GtkWidget *textwidget, int line, int posn, int cc)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   ch             *txline, *pp1, *pp2;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   txline = textwidget_line(textwidget,line,0);
   if (! txline) return;

   pp1 = txline + posn;
   pp2 = pp1 + cc - 1;
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter1,line,pp1-txline);
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter2,line,pp2-txline+1);
   gtk_text_buffer_select_range(textBuff,&iter1,&iter2);

   zfree(txline);
   return;
}


//  convert text to bold text at line, positiion, cc

void textwidget_bold_word(GtkWidget *textwidget, int line, int posn, int cc)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   GtkTextTag     *fontag = 0;
   ch             *boldfont = zfuncs::appmonoboldfont;
   ch             *txline, *pp1, *pp2;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   txline = textwidget_line(textwidget,line,0);
   if (! txline) return;

   fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,0);

   /***
   fontag = gtk_text_buffer_create_tag(textBuff,0,"font",boldfont,               //  example
                       "foreground","red","background","light blue",0);
   ***/

   pp1 = txline + posn;
   pp2 = pp1 + cc - 1;
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter1,line,pp1-txline);
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter2,line,pp2-txline+1);
   gtk_text_buffer_apply_tag(textBuff,fontag,&iter1,&iter2);

   zfree(txline);
   return;
}


//  convert text to underlined text at line, positiion, cc

void textwidget_underline_word(GtkWidget *textwidget, int line, int posn, int cc)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   GtkTextTag     *fontag = 0;
   ch             *txline, *pp1, *pp2;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   txline = textwidget_line(textwidget,line,0);
   if (! txline) return;

   fontag = gtk_text_buffer_create_tag(textBuff,0,"underline",PANGO_UNDERLINE_SINGLE,0);

   pp1 = txline + posn;
   pp2 = pp1 + cc - 1;
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter1,line,pp1-txline);
   gtk_text_buffer_get_iter_at_line_index(textBuff,&iter2,line,pp2-txline+1);
   gtk_text_buffer_apply_tag(textBuff,fontag,&iter1,&iter2);

   zfree(txline);
   return;
}


//  set font attributes for the entire textwidget (black on white)
//  this does not do anything to the text font - why?                            FIXME

void textwidget_font_attributes(GtkWidget *textwidget)
{
   GtkTextBuffer  *textBuff;
   GtkTextIter    iter1, iter2;
   GtkTextTag     *fontag = 0;

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textwidget));
   if (! textBuff) return;

   fontag = gtk_text_buffer_create_tag(textBuff,0,                               //  high contrast
         "font",appmonofont,"foreground","black","background","white",0);

   gtk_text_buffer_get_start_iter(textBuff,&iter1);
   gtk_text_buffer_get_end_iter(textBuff,&iter2);

   gtk_text_buffer_apply_tag(textBuff,fontag,&iter1,&iter2);

   return;
}


//  set an event function for mouse and KB events in textwidget
//    + line selection via mouse click or keyboard up/down arrow key
//    + line and word selection via mouse click
//
//  optional user callback function looks like this:
//    void userfunc(GtkWidget *textwidget, int line, int position, int KBkey)
//  this function receives KB keys and mouse click text line/position

void textwidget_set_eventfunc(GtkWidget *textwidget, textwidget_callbackfunc_t userfunc)
{
   int textwidget_eventfunc(GtkWidget *textwidget, GdkEvent *event, textwidget_callbackfunc_t userfunc);

   gtk_widget_add_events(textwidget,GDK_BUTTON_PRESS_MASK);
   gtk_widget_add_events(textwidget,GDK_KEY_PRESS_MASK);
   gtk_widget_add_events(textwidget,GDK_POINTER_MOTION_MASK);
   gtk_widget_add_events(textwidget,GDK_FOCUS_CHANGE_MASK);
   G_SIGNAL(textwidget,"key-press-event",textwidget_eventfunc,userfunc);
   G_SIGNAL(textwidget,"button-press-event",textwidget_eventfunc,userfunc);
   G_SIGNAL(textwidget,"motion-notify-event",textwidget_eventfunc,userfunc);
   G_SIGNAL(textwidget,"focus-in-event",textwidget_eventfunc,userfunc);
   return;
}


//  textwidget event function:
//  if no user callback function, process KB navigation keys (arrow, page, home/end)
//  if user callback func, send all KB keys to user callback function
//  process mouse clicks, send clicked line and position to user callback function

int textwidget_eventfunc(GtkWidget *textwidget, GdkEvent *event, textwidget_callbackfunc_t userfunc)
{
   #define TEXT GTK_TEXT_WINDOW_TEXT
   #define VIEW GTK_TEXT_VIEW

   static GdkCursor  *arrowcursor = 0;
   GdkWindow         *gdkwin;
   GtkTextIter       iter1;
   int               button, mpx, mpy, tbx, tby;
   int               line, pos, vtop, vbott, page, KBkey;

   if (! arrowcursor)                                                            //  first call, get arrow cursor
      arrowcursor = gdk_cursor_new_for_display(display,GDK_TOP_LEFT_ARROW);
   gdkwin = gtk_text_view_get_window(VIEW(textwidget),TEXT);                     //  set arrow cursor for window
   if (gdkwin) gdk_window_set_cursor(gdkwin,arrowcursor);                        //  (must reset every event)

   gtk_widget_grab_focus(textwidget);

   if (event->type == GDK_KEY_PRESS)                                             //  KB key press event
   {
      KBkey = ((GdkEventKey *) event)->keyval;

      if (userfunc) {
         userfunc(textwidget,-1,-1,KBkey);
         return 1;
      }

      if (KBkey >= 0xfd00)                                                       //  navigation key
      {
         textwidget_get_visible_lines(textwidget,vtop,vbott);                    //  range of lines on screen
         page = vbott - vtop - 2;                                                //  page size, lines
         if (page < 0) page = 0;
         line = 0;                                                               //  default
         if (KBkey == GDK_KEY_Up) line = vtop - 1;                               //  handle some navigation keys
         else if (KBkey == GDK_KEY_Down) line = vbott + 1;
         else if (KBkey == GDK_KEY_Page_Up) line = vtop - page;
         else if (KBkey == GDK_KEY_Page_Down) line = vbott + page;
         else if (KBkey == GDK_KEY_Home) line = 0;
         else if (KBkey == GDK_KEY_End) line = 999999;
         if (line < 0) line = 0;
         textwidget_scroll(textwidget,line);                                     //  put line on screen
      }

      return 1;
   }

   if (! userfunc) return 0;

   if (event->type == GDK_BUTTON_PRESS)                                          //  mouse button press
   {
      button = ((GdkEventButton *) event)->button;                               //  ignore if not left button
      if (button != 1) return 0;
      mpx = int(((GdkEventButton *) event)->x);                                  //  mouse click position
      mpy = int(((GdkEventButton *) event)->y);
      mpx -= appfontsize / 2;                                                    //  more accurate
      if (mpx < 0) mpx = 0;
      gtk_text_view_window_to_buffer_coords(VIEW(textwidget),TEXT,mpx,mpy,&tbx,&tby);
      if (tbx && tby) {                                                          //  can happen
         gtk_text_view_get_iter_at_location(VIEW(textwidget),&iter1,tbx,tby);
         line = gtk_text_iter_get_line(&iter1);                                  //  clicked textwidget line
         pos = gtk_text_iter_get_line_offset(&iter1);                            //  clicked position
      }
      else line = pos = 0;
      userfunc(textwidget,line,pos,-1);                                          //  pass line and posn to user func
      return 1;
   }

   return 0;
}


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

   simplified GTK menu bar, tool bar, status bar functions

   These functions simplify the creation of GTK menus and toolbars.
   The functionality is limited but adequate for most purposes.

   mbar = create_menubar(vbox)                               create menubar
   mitem = add_menubar_item(mbar, label, func)               add menu item to menubar
   msub = add_submenu_item(mitem, label, func, tip)          add submenu item to menu or submenu

   tbar = create_toolbar(vbox, iconsize)                     create toolbar
   add_toolbar_button(tbar, label, tip, icon, func)          add button to toolbar

   stbar = create_stbar(vbox)                                create status bar
   stbar_message(stbar, message)                             display message in status bar

   These functions to the following:
      * create a menu bar and add to existing window vertical packing box
      * add menu item to menu bar
      * add submenu item to menu bar item or submenu item
      * create a toolbar and add to existing window
      * add button to toolbar, using stock icon or custom icon
      * create a status bar and add to existing window
      * display a message in the status bar

   argument definitions:
     vbox         GtkWidget *    a vertical packing box (in a window)
     mbar         GtkWidget *    reference for menu bar
     popup        GtkWidget *    reference for popup menu
     mitem        GtkWidget *    reference for menu item (in a menu bar)
     msub         GtkWidget *    reference for submenu item (in a menu)
     label        ch *           menu or toolbar name or label
     tbar         GtkWidget *    reference for toolbar
     tip          ch *           tool button tool tip (popup text via mouse-over)
     icon         ch *           stock icon name or custom icon file name (see below)
     func         see below      menu or tool button response function
     arg          ch *           argument to response function
     stbar        int            reference for status bar
     message      ch *           message to display in status bar

   The icon argument for the function add_toolbar_button() has two forms.
   For a GTK stock item referenced with a macro like GTK_STOCK_OPEN, use the
   corresponding text name, like "gtk-open".

   For a custom icon, use the icon's file name like "my-icon.png".
   The file is expected to be in  get_zdatadir()/icons.
   The icon file may be any size, and is resized for use on the toolbar.
   If the file is not found, the stock icon "gtk-missing-image" is used
   (".png" and ".jpg" files both work).

   For a button with no icon (text label only), use 0 or null for the icon argument.
   For a menu separator, use the menu name "separator".
   For a toolbar separator, use the label "separator".
   For a title menu (no response function), set the response function to null.

   The response function for both menus and toolbar buttons looks like this:
       void func(GtkWidget *, ch *)

   The following macro is also supplied to simplify the coding of response functions:
   G_SIGNAL(window,event,func,arg)   which expands to:
   g_signal_connect(G_OBJECT(window),event,G_CALLBACK(func),(void *) arg)

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

//  create menu bar and add to vertical packing box

GtkWidget * create_menubar(GtkWidget *vbox)
{
   GtkWidget   *wmbar;

   wmbar = gtk_menu_bar_new();
   gtk_box_pack_start(GTK_BOX(vbox),wmbar,0,0,0);
   return wmbar;
}


//  add menu item to menu bar, with optional response function

GtkWidget * add_menubar_item(GtkWidget *wmbar, ch *mname, cbFunc func)
{
   GtkWidget   *wmitem;

   wmitem = gtk_menu_item_new_with_label(mname);
   gtk_menu_shell_append(GTK_MENU_SHELL(wmbar),wmitem);
   if (func) G_SIGNAL(wmitem,"activate",func,mname);
   return  wmitem;
}


//  add submenu item to menu item, with optional response function

GtkWidget * add_submenu_item(GtkWidget *wmitem, ch *mlab, cbFunc func, ch *mtip)
{
   GtkWidget      *wmsub, *wmsubitem;

   wmsub = gtk_menu_item_get_submenu(GTK_MENU_ITEM(wmitem));                     //  add submenu if not already
   if (wmsub == null) {
      wmsub = gtk_menu_new();
      gtk_menu_item_set_submenu(GTK_MENU_ITEM(wmitem),wmsub);
   }

   if (strmatch(mlab,"separator"))
      wmsubitem = gtk_separator_menu_item_new();
   else  wmsubitem = gtk_menu_item_new_with_label(mlab);                         //  add menu item with label only

   gtk_menu_shell_append(GTK_MENU_SHELL(wmsub),wmsubitem);                       //  append submenu item to submenu

   if (func) G_SIGNAL(wmsubitem,"activate",func,mlab);                           //  connect optional response function

   if (mtip) g_object_set(G_OBJECT(wmsubitem),"tooltip-text",mtip,null);         //  add optional popup menu tip

   return  wmsubitem;
}


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

//  create toolbar and add to vertical packing box

int      tbIconSize = 32;                                                        //  default if not supplied

GtkWidget * create_toolbar(GtkWidget *vbox, int iconsize)
{
   GtkWidget   *wtbar;

   wtbar = gtk_toolbar_new();
   gtk_box_pack_start(GTK_BOX(vbox),wtbar,0,0,0);
   tbIconSize = iconsize;
   return  wtbar;
}


//  add toolbar button with label and icon ("iconfile.png") and tool tip
//  at least one of label and icon should be present

GtkWidget * add_toolbar_button(GtkWidget *wtbar, ch *blab, ch *btip, ch *icon, cbFunc func)
{
   GtkToolItem    *tbutton;
   GError         *gerror = 0;
   PIXBUF         *pixbuf;
   GtkWidget      *wicon = 0;
   ch             iconpath[300], *pp;
   STATB          statB;
   int            err, cc;

   if (blab && strmatch(blab,"separator")) {
      tbutton = gtk_separator_tool_item_new();
      gtk_toolbar_insert(GTK_TOOLBAR(wtbar),GTK_TOOL_ITEM(tbutton),-1);
      return  (GtkWidget *) tbutton;
   }

   if (icon && *icon) {                                                          //  get icon pixbuf
      *iconpath = 0;
      strncatv(iconpath,199,zimagedir,"/",icon,null);
      err = stat(iconpath,&statB);
      if (err) {                                                                 //  alternative path
         cc = readlink("/proc/self/exe",iconpath,300);                           //  get own program path
         if (cc > 0) iconpath[cc] = 0;                                           //  readlink() quirk
         pp = strrchr(iconpath,'/');                                             //  folder of program
         if (pp) *pp = 0;
         strncatv(iconpath,300,"/icons/",icon,null);                             //  .../icons/iconfile.png
      }
      pixbuf = gdk_pixbuf_new_from_file_at_scale(iconpath,tbIconSize,tbIconSize,1,&gerror);
      if (pixbuf) wicon = gtk_image_new_from_pixbuf(pixbuf);
   }

   tbutton = gtk_tool_button_new(wicon,blab);
   if (! wicon) gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tbutton),"gtk-missing-image");

   if (btip) gtk_tool_item_set_tooltip_text(tbutton,btip);
   gtk_tool_item_set_homogeneous(tbutton,0);
   gtk_toolbar_insert(GTK_TOOLBAR(wtbar),GTK_TOOL_ITEM(tbutton),-1);
   if (func) G_SIGNAL(tbutton,"clicked",func,blab);
   return  (GtkWidget *) tbutton;
}


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

//  create a status bar and add to the start of a packing box

GtkWidget * create_stbar(GtkWidget *pbox)
{
   GtkWidget      *stbar;

   stbar = gtk_statusbar_new();
   gtk_box_pack_start(GTK_BOX(pbox),stbar,0,0,0);
   gtk_widget_show(stbar);
   return  stbar;
}


//  display message in status bar

int stbar_message(GtkWidget *wstbar, ch *message)
{
   static int     ctx = -1;

   if (ctx == -1)
      ctx = gtk_statusbar_get_context_id(GTK_STATUSBAR(wstbar),"all");
   gtk_statusbar_pop(GTK_STATUSBAR(wstbar),ctx);
   gtk_statusbar_push(GTK_STATUSBAR(wstbar),ctx,message);
   return 0;
}


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

   Popup Menu

   GtkWidget   *popup, *mitem
   ch          *label, *arg, *tip
   void func(GtkWidget *, ch *arg)

   popup = create_popmenu()                                  create a popup menu
   mitem = add_popmenu_item(popup, label, func, arg, tip)    add menu item to popup menu
   popup_menu(GtkWidget *parent, popup)                      popup the menu at mouse position

   Call 'create_popmenu' and then 'add_popmenu_item' for each item in the menu.
   'label' is the menu name, 'func' the response function, 'arg' an argument
   for 'func', and 'tip' is a tool-tip. 'arg' and 'tip' may be null.
   A call to 'popup_menu' will show all menu entries at the mouse position.
   Clicking an entry will call the respective response function.
   Hovering on the entry will show the tool-tip.

   The response function looks like this:
       void func(GtkWidget *, ch *menu)

***/

//  create a popup menu

GtkWidget * create_popmenu()                                                     //  event processing removed              24.60
{
   int popmenu_event(GtkWidget *, GdkEvent *);

   GtkWidget   *popmenu;
   popmenu = gtk_menu_new();
   return popmenu;
}


//  add a menu item to a popup menu

GtkWidget * add_popmenu_item(GtkWidget *popmenu, ch *mname, cbFunc func, ch *arg, ch *mtip)
{
   void popmenu_item_select(GtkWidget *, ch *mtip);

   GtkWidget   *widget;

   widget = gtk_menu_item_new_with_label(mname);
   gtk_menu_shell_append(GTK_MENU_SHELL(popmenu),widget);

   if (func) {
      if (arg) G_SIGNAL(widget,"activate",func,arg);                             //  call func with arg
      else G_SIGNAL(widget,"activate",func,mname);                               //  call func with menu name
   }

   if (mtip) {
      G_SIGNAL(widget,"select",popmenu_item_select,mtip);
      G_SIGNAL(widget,"deselect",popmenu_item_select,0);
   }

   return widget;
}


//  show popup tip for selected menu item

void popmenu_item_select(GtkWidget *wmitem, ch *mtip)                            //  convoluted code but it works
{
   GdkWindow   *window;
   int         xp, yp, mx, my;

   window = gtk_widget_get_window(wmitem);
   gdk_window_get_origin(window,&xp,&yp);                                        //  menu screen origin
   xp += gdk_window_get_width(window);                                           //   + width
   gdk_device_get_position(zfuncs::mouse,0,&mx,&my);                             //  mouse (x,y) screen position
   poptext_screen(mtip,xp,my,0,5);                                               //  popup px = menu + width, py = mouse
   return;
}


//  Show a popup menu at current mouse position
//  GtkWidget *  argument is not used

void popup_menu(GtkWidget *widget, GtkWidget *popmenu)
{
   gtk_widget_show_all(popmenu);                                                 //  GTK change: show before popup
   gtk_menu_popup_at_pointer(GTK_MENU(popmenu),null);
   return;
}


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

   Vertical Menu / Toolbar

   Build a custom vertical menu and/or toolbar in a vertical packing box

   Vmenu    *vbm;
   ch       *name, *icon, *desc, *arg;
   int      iww, ihh;

   void func(GtkWidget *, ch *name);
   void RMfunc(GtkWidget *, ch *name);

   vbm = Vmenu_new(GtkWidget *vbox, float fgRGB[3], float bgRGB[3]);             //  create base menu

   Vmenu_add(vbm, name, icon, iww, ihh, desc, func, arg);                        //  add left-mouse menu function

   Vmenu_add_setupfunc(vbm, me, func);                                           //  add opt. setup function
   Vmenu_add_RMfunc(vbm, me, func);                                              //  add right-mouse menu function

   Vmenu_block(int flag)      1 to block Vmenu, 0 to unblock

   Create a vertical menu / toolbar in a vertical packing box.
   fgRGB and bgRGB are font and background colors, RGB scaled 0-1.0
   Added items can have a menu name, icon, description, response function,
   and function argument. 'name' and 'icon' can be null but not both.

   name        menu name
   icon        menu icon, filespec for a .png file
   iww, ihh    size of icon in menu display
   desc        optional tool tip if mouse is hovered over displayed menu

   When 'name/icon' is clicked, 'func' is called with 'arg'.
   If 'arg' is null, 'name' is used instead.

   To create a menu entry that is a popup menu with multiple entries, do as follows:
        popup = create_popmenu();
        add_popup_menu_item(popup ...);         see create_popmenu()
        add_popup_menu_item(popup ...);
        ...
        Vmenu_add(vbm, name, icon, ww, hh, desc, create_popmenu, (ch *) popup);

   i.e. use create_popmenu() as the response function and use the previously
        created menu 'popup' as the argument (cast to ch *).

***/


namespace Vmenunames
{
   #define margin 5                                                              //  margins for menu text

   PangoFontDescription    *pfont1, *pfont2;
   PangoAttrList           *pattrlist;
   PangoAttribute          *pbackground;
   int      fontheight;
   int      Fblock = 0;

   void  wpaint(GtkWidget *, cairo_t *, Vmenu *);                                //  window repaint - draw event
   void  mouse_event(GtkWidget *, GdkEventButton *, Vmenu *);                    //  mouse event function
   void  paint_menu(cairo_t *cr, Vmenu *vbm, int me, int hilite);                //  paint menu entry, opt. highlight
}


//  create Vmenu

Vmenu *Vmenu_new(GtkWidget *vbox, float fgRGB[3], float bgRGB[3])
{
   using namespace Vmenunames;

   int      cc, ww, hh;
   int      K64 = 65536;
   ch       *menufont1, *menufont2;
   PangoLayout   *playout;

   cc = sizeof(Vmenu);
   Vmenu *vbm = (Vmenu *) zmalloc(cc,"Vmenu");
   vbm->fgRGB[0] = fgRGB[0];                                                     //  background color, RGB 0-1.0
   vbm->fgRGB[1] = fgRGB[1];
   vbm->fgRGB[2] = fgRGB[2];
   vbm->bgRGB[0] = bgRGB[0];                                                     //  background color, RGB 0-1.0
   vbm->bgRGB[1] = bgRGB[1];
   vbm->bgRGB[2] = bgRGB[2];
   vbm->vbox = vbox;
   vbm->topwin = gtk_widget_get_toplevel(vbox);
   vbm->layout = gtk_layout_new(0,0);
   vbm->mcount = 0;
   gtk_box_pack_start(GTK_BOX(vbox),vbm->layout,1,1,0);
   vbm->xmax = vbm->ymax = 10;                                                   //  initial layout size

   pattrlist = pango_attr_list_new();
   pbackground = pango_attr_background_new(K64*bgRGB[0],K64*bgRGB[1],K64*bgRGB[2]);
   pango_attr_list_change(pattrlist,pbackground);

   menufont1 = zstrdup(zfuncs::appfont,"Vmenu");                                 //  set menu fonts, normal and bold
   menufont2 = zstrdup(zfuncs::appboldfont,"Vmenu");

   pfont1 = pango_font_description_from_string(menufont1);
   pfont2 = pango_font_description_from_string(menufont2);

   playout = gtk_widget_create_pango_layout(vbm->layout,0);
   pango_layout_set_font_description(playout,pfont1);
   pango_layout_set_text(playout,"Ayg",-1);
   pango_layout_get_pixel_size(playout,&ww,&hh);
   fontheight = hh;

   gtk_widget_add_events(vbm->layout,GDK_BUTTON_PRESS_MASK);
   gtk_widget_add_events(vbm->layout,GDK_BUTTON_RELEASE_MASK);
   gtk_widget_add_events(vbm->layout,GDK_POINTER_MOTION_MASK);
   gtk_widget_add_events(vbm->layout,GDK_LEAVE_NOTIFY_MASK);
   G_SIGNAL(vbm->layout,"button-press-event",mouse_event,vbm);
   G_SIGNAL(vbm->layout,"button-release-event",mouse_event,vbm);
   G_SIGNAL(vbm->layout,"motion-notify-event",mouse_event,vbm);
   G_SIGNAL(vbm->layout,"leave-notify-event",mouse_event,vbm);
   G_SIGNAL(vbm->layout,"draw",wpaint,vbm);

   return vbm;
}


//  add Vmenu entry with name, icon, description, menu function (left click)

void Vmenu_add(Vmenu *vbm, ch *name, ch *icon, int iconww, int iconhh, ch *desc, cbFunc func, ch *arg)
{
   using namespace Vmenunames;

   int         me, cc, xpos, ww, hh;
   ch          iconpath[200], *mdesc, *name__;
   ch          *blanks = "                    ";                                 //  20 blanks
   PIXBUF      *pixbuf;
   GError      *gerror = 0;

   PangoLayout             *playout;
   PangoFontDescription    *pfont;

   if (! name && ! icon) return;

   me = vbm->mcount++;                                                           //  track no. menu entries

   if (name) vbm->menu[me].name = zstrdup(name,"Vmenu");                         //  create new menu entry from caller data

   if (icon) {
      vbm->menu[me].icon = zstrdup(icon,"Vmenu");
      vbm->menu[me].iconww = iconww;
      vbm->menu[me].iconhh = iconhh;
   }

   if (desc) {                                                                   //  pad description with blanks for looks
      cc = strlen(desc);
      mdesc = (ch *) zmalloc(cc+3,"Vmenu");
      mdesc[0] = ' ';
      strcpy(mdesc+1,desc);
      strcpy(mdesc+cc+1," ");
      vbm->menu[me].desc = mdesc;
   }

   vbm->menu[me].LMfunc = func;                                                  //  left-mouse menu function
   vbm->menu[me].arg = name;                                                     //  argument is menu name or arg if avail.
   if (arg) vbm->menu[me].arg = arg;

   vbm->menu[me].pixbuf = 0;

   if (icon) {                                                                   //  if icon is named, get pixbuf
      *iconpath = 0;
      strncatv(iconpath,199,zfuncs::zimagedir,"/",icon,null);
      pixbuf = gdk_pixbuf_new_from_file_at_scale(iconpath,iconww,iconhh,1,&gerror);
      if (pixbuf) vbm->menu[me].pixbuf = pixbuf;
      else Plog(1,"Vmenu no icon: %s \n",iconpath);
   }

   if (me == 0) vbm->ymax = margin;                                              //  first menu, top position

   vbm->menu[me].iconx = 0;
   vbm->menu[me].icony = 0;
   vbm->menu[me].namex = 0;
   vbm->menu[me].namey = 0;

   if (icon) {
      vbm->menu[me].iconx = margin;                                              //     ______
      vbm->menu[me].icony = vbm->ymax;                                           //    |      |
      if (name) {                                                                //    | icon | menu name
         vbm->menu[me].namex = margin + iconww + margin;                         //    |______|
         vbm->menu[me].namey = vbm->ymax + (iconhh - fontheight) / 2;            //
      }
      vbm->menu[me].ylo = vbm->ymax;
      vbm->ymax += iconhh + iconhh / 8;                                          //  position for next menu entry
      vbm->menu[me].yhi = vbm->ymax;
      if (margin + iconww > vbm->xmax) vbm->xmax = margin + iconww;              //  keep track of max. layout width
   }

   else if (name) {
      vbm->menu[me].namex = margin;                                              //  menu name
      vbm->menu[me].namey = vbm->ymax;
      vbm->menu[me].ylo = vbm->ymax;
      vbm->ymax += 1.5 * fontheight;                                             //  more space between text lines
      vbm->menu[me].yhi = vbm->ymax;
   }

   vbm->menu[me].playout1 = gtk_widget_create_pango_layout(vbm->layout,0);
   vbm->menu[me].playout2 = gtk_widget_create_pango_layout(vbm->layout,0);

   if (name) {
      xpos = vbm->menu[me].namex;

      cc = strlen(name);                                                         //  menu name with trailing blanks
      name__ = zstrdup(name,"Vmenu",22);                                         //  (long enough to overwrite bold name)
      strncpy0(name__+cc,blanks,20);

      playout = vbm->menu[me].playout1;                                          //  normal font
      pfont = pfont1;
      pango_layout_set_attributes(playout,pattrlist);
      pango_layout_set_font_description(playout,pfont);
      pango_layout_set_text(playout,name__,-1);                                  //  compute layout
      pango_layout_get_pixel_size(playout,&ww,&hh);                              //  pixel width and height of layout

      playout = vbm->menu[me].playout2;                                          //  bold font
      pfont = pfont2;
      pango_layout_set_attributes(playout,pattrlist);
      pango_layout_set_font_description(playout,pfont);
      pango_layout_set_text(playout,name,-1);                                    //  compute layout
      pango_layout_get_pixel_size(playout,&ww,&hh);                              //  pixel width and height of layout
      if (xpos + ww > vbm->xmax) vbm->xmax = xpos + ww;                          //  keep track of max. layout width
   }

   gtk_widget_set_size_request(vbm->layout,vbm->xmax+margin,0);                  //  add right margin to layout width

   return;
}


//  add opt. setup function to existing menu entry

void Vmenu_add_setup(Vmenu *vbm, int me, cbFunc func, ch *arg)
{
   if (me > vbm->mcount-1) zappcrash("Vmenu_add_RMfunc() bad me: %d",me);
   vbm->menu[me].setupfunc = func;
   vbm->menu[me].setuparg = arg;
   return;
}


//  add alternate function for right-mouse click

void Vmenu_add_RMfunc(Vmenu *vbm, int me, cbFunc func, ch *arg)
{
   if (me > vbm->mcount-1) zappcrash("Vmenu_add_RMfunc() bad me: %d",me);
   vbm->menu[me].RMfunc = func;
   vbm->menu[me].RMarg = arg;
   return;
}


//  block or unblock menu

void Vmenu_block(int flag)
{
   using namespace Vmenunames;

   Fblock = flag;
   return;
}


//  paint window when created, exposed, resized

void Vmenunames::wpaint(GtkWidget *widget, cairo_t *cr, Vmenu *vbm)
{
   using namespace Vmenunames;

   cairo_set_source_rgb(cr,vbm->bgRGB[0],vbm->bgRGB[1],vbm->bgRGB[2]);           //  background
   cairo_paint(cr);

   for (int me = 0; me < vbm->mcount; me++)                                      //  paint all menu entries
      paint_menu(cr,vbm,me,0);

   return;
}


//  draw menu icon and text into layout

void Vmenunames::paint_menu(cairo_t *cr, Vmenu *vbm, int me, int hilite)
{
   using namespace Vmenunames;

   PIXBUF         *pixbuf;
   PangoLayout    *playout;
   int            xpos, ypos;
   int            iconww, iconhh;
   ch             *name;

   pixbuf = vbm->menu[me].pixbuf;                                                //  icon
   if (pixbuf) {                                                                 //  draw menu icon at menu position
      xpos = vbm->menu[me].iconx;
      ypos = vbm->menu[me].icony;
      iconww = vbm->menu[me].iconww;
      iconhh = vbm->menu[me].iconhh;

      if (! hilite) {                                                            //  erase box around icon
         cairo_set_source_rgb(cr,vbm->bgRGB[0],vbm->bgRGB[1],vbm->bgRGB[2]);     //  background
         cairo_rectangle(cr,xpos-1,ypos-1,iconww+2,iconhh+2);
         cairo_fill(cr);
      }

      gdk_cairo_set_source_pixbuf(cr,pixbuf,xpos,ypos);                          //  draw icon
      cairo_paint(cr);

      if (hilite) {
         cairo_set_source_rgb(cr,vbm->fgRGB[0],vbm->fgRGB[1],vbm->fgRGB[2]);     //  draw box around icon
         cairo_set_line_width(cr,1);
         cairo_set_line_join(cr,CAIRO_LINE_JOIN_ROUND);
         cairo_rectangle(cr,xpos,ypos,iconww,iconhh);
         cairo_stroke(cr);
      }
   }

   name = vbm->menu[me].name;                                                    //  menu text
   if (name) {                                                                   //  draw menu text at menu position
      xpos = vbm->menu[me].namex;
      ypos = vbm->menu[me].namey;
      cairo_move_to(cr,xpos,ypos);                                               //  draw layout with text
      cairo_set_source_rgb(cr,vbm->fgRGB[0],vbm->fgRGB[1],vbm->fgRGB[2]);
      if (hilite) playout = vbm->menu[me].playout2;
      else playout = vbm->menu[me].playout1;
      pango_cairo_show_layout(cr,playout);
   }

   return;
}


//  mouse event function - capture buttons and drag movements

void Vmenunames::mouse_event(GtkWidget *widget, GdkEventButton *event, Vmenu *vbm)
{
   using namespace Vmenunames;

   GdkWindow   *gdkwin;
   ch          *desc;
   int         me, mpx, mpy, button, ww, ylo, yhi;
   static int  me0 = -1, Fmyclick = 0, winww = 0;

   static draw_context_t   context;
   static GtkWidget        *pwidget = 0;
   static cairo_t          *cr = 0;

   if (widget != pwidget) {                                                      //  widget changed
      if (pwidget) draw_context_destroy(context);
      gdkwin = gtk_layout_get_bin_window(GTK_LAYOUT(widget));
      cr = draw_context_create(gdkwin,context);
      gdkwin = gtk_widget_get_window(widget);                                    //  get width of menu widget
      winww = gdk_window_get_width(gdkwin);
      pwidget = widget;
   }

   mpx = int(event->x);                                                          //  mouse position
   mpy = int(event->y);
   button = event->button;
   if (button == 1 && (event->state & GDK_MOD1_MASK)) button = 3;                //  left butt + ALT key >> right butt

   if (event->type == GDK_MOTION_NOTIFY)                                         //  mouse inside layout
   {
      for (me = 0; me < vbm->mcount; me++) {                                     //  find menu where mouse is
         ylo = vbm->menu[me].ylo;
         yhi = vbm->menu[me].yhi;
         if (mpy < ylo) continue;
         if (mpy < yhi) break;
      }

      if (me != me0 && me0 >= 0) {                                               //  unhighlight prior
         paint_menu(cr,vbm,me0,0);
         me0 = -1;
      }

      if (me == me0) return;                                                     //  same as before
      if (me == vbm->mcount) return;                                             //  no new menu match

      paint_menu(cr,vbm,me,1);                                                   //  highlight menu entry at mouse
      desc = vbm->menu[me].desc;                                                 //  show tool tip
      if (desc) poptext_widget(widget,desc,winww,mpy,1,10);                      //  px = menu width, py = mouse
      me0 = me;                                                                  //  remember last match
      return;
   }

   if (me0 >= 0)                                                                 //  mouse left layout
   {
      paint_menu(cr,vbm,me0,0);                                                  //  unhighlight prior
      desc = vbm->menu[me0].desc;                                                //  remove prior tool tip
      if (desc) poptext_mouse(0,0,0,0,0);
      me0 = -1;
   }

   if (event->type == GDK_BUTTON_PRESS)                                          //  menu entry clicked
      Fmyclick = 1;                                                              //  button click is mine

   if (event->type == GDK_BUTTON_RELEASE)                                        //  menu entry clicked
   {
      if (Fblock) return;                                                        //  menu is blocked

      if (! Fmyclick) return;                                                    //  ignore unmatched button release
      Fmyclick = 0;                                                              //    (from vanished popup window)

      for (me = 0; me < vbm->mcount; me++) {                                     //  look for clicked menu entry
         ylo = vbm->menu[me].ylo;
         yhi = vbm->menu[me].yhi;
         if (mpy < ylo) continue;
         if (mpy < yhi) break;
      }

      if (me == vbm->mcount) return;                                             //  no menu match

      zfuncs::vmenuclickbutton = button;                                         //  1/2/3 = left/mid/right button

      ww = vbm->menu[me].iconww;                                                 //  get horiz. click posn. on menu icon
      if (ww) mpx = 100 * (mpx - margin) / ww;                                   //    scale 0-100
      else mpx = 0;
      if (mpx < 0) mpx = 0;
      if (mpx > 100) mpx = 100;
      zfuncs::vmenuclickposn = mpx;

      paint_menu(cr,vbm,me,0);                                                   //  unhighlight menu

      if (vbm->menu[me].setupfunc) {                                             //  call opt. setup function
         vbm->menu[me].setupfunc(widget,vbm->menu[me].setuparg);
         if (vmenustop) {
            vmenustop = 0;
            return;
         }
      }

      if (button == 3 && vbm->menu[me].RMfunc)                                   //  if right mouse button,
         vbm->menu[me].RMfunc(widget,vbm->menu[me].RMarg);                       //    call right-mouse function

      else if (vbm->menu[me].LMfunc)                                             //  call left-mouse menu function
         vbm->menu[me].LMfunc(widget,vbm->menu[me].arg);
   }

   return;
}


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

   spline curve setup and edit functions
   support multiple frames with multiple curves

   sd = splcurve_init(frame,callback_func)            add draw area widget in dialog frame widget
   sd->Nspc = n                                       Initialize no. of curves in frame
   sd->fact[spc] = 1                                  Initialize active flag for curve spc
   sd->vert[spc] = hv                                 Initialize vert/horz flag for curve spc
   sd->nap[spc], sd->apx[spc][xx], sd->apy[spc][yy]   Initialize anchor points for curve spc
   splcurve_generate(sd,spc)                          Generate data for curve spc

   Curves will now be shown inside the frame when window is realized.
   The callback_func(spc) will be called when curve spc is edited (mouse drag).
   Change curve in program: set anchor points, call splcurve_generate(sd,spc).

   yval = splcurve_yval(sd,spc,xval)            Get y-value (0-1) for curve spc and given x-value (0-1)

   kk = 1000 * xval;                            If faster access to curve is needed (no interpolation)
   if (kk > 999) kk = 999;
   yval = sd->yval[spc][kk];

***/

//  initialize for spline curve editing
//  initial anchor points are pre-loaded into spldat before window is realized

spldat * splcurve_init(GtkWidget *frame, void func(int spc))
{
   int      cc = sizeof(spldat);                                                 //  allocate spc curve data area
   spldat * sd = (spldat *) zmalloc(cc,"splcurve");
   memset(sd,0,cc);

   sd->drawarea = gtk_drawing_area_new();                                        //  drawing area for curves
   gtk_container_add(GTK_CONTAINER(frame),sd->drawarea);
   sd->spcfunc = func;                                                           //  user callback function

   gtk_widget_add_events(sd->drawarea,GDK_BUTTON_PRESS_MASK);                    //  connect mouse events to drawing area
   gtk_widget_add_events(sd->drawarea,GDK_BUTTON_RELEASE_MASK);
   gtk_widget_add_events(sd->drawarea,GDK_BUTTON1_MOTION_MASK);
   G_SIGNAL(sd->drawarea,"motion-notify-event",splcurve_adjust,sd);
   G_SIGNAL(sd->drawarea,"button-press-event",splcurve_adjust,sd);
   G_SIGNAL(sd->drawarea,"realize",splcurve_resize,sd);
   G_SIGNAL(sd->drawarea,"draw",splcurve_draw,sd);

   return sd;
}


//  modify anchor points in curve using mouse

int splcurve_adjust(void *, GdkEventButton *event, spldat *sd)
{
   int            ww, hh, kk;
   int            mx, my, button, evtype;
   static int     spc, ap, mbusy = 0, Fdrag = 0;                                 //  drag continuation logic
   int            minspc, minap, apset = 0;
   float          mxval, myval, cxval, cyval;
   float          dist2, mindist2 = 0;
   float          dist, dx, dy;
   float          minx = 0.01 * splcurve_minx;                                   //  % to absolute distance

   mx = event->x;                                                                //  mouse position in drawing area
   my = event->y;
   evtype = event->type;
   button = event->button;

   if (evtype == GDK_MOTION_NOTIFY) {
      if (mbusy) return 0;                                                       //  discard excess motion events
      mbusy++;
      zmainloop();
      mbusy = 0;
   }

   if (evtype == GDK_BUTTON_RELEASE) {
      Fdrag = 0;
      return 0;
   }

   ww = gtk_widget_get_allocated_width(sd->drawarea);                            //  drawing area size
   hh = gtk_widget_get_allocated_height(sd->drawarea);

   if (mx < 0) mx = 0;                                                           //  limit edge excursions
   if (mx > ww) mx = ww;
   if (my < 0) my = 0;
   if (my > hh) my = hh;

   if (evtype == GDK_BUTTON_PRESS) Fdrag = 0;                                    //  left or right click

   if (Fdrag)                                                                    //  continuation of drag
   {
      if (sd->vert[spc]) {
         mxval = 1.0 * my / hh;                                                  //  mouse position in curve space
         myval = 1.0 * mx / ww;
      }
      else {
         mxval = 1.0 * mx / ww;
         myval = 1.0 * (hh - my) / hh;
      }

      if (ap < sd->nap[spc] - 1) {                                               //  not the last anchor point
         dx = sd->apx[spc][ap+1] - mxval;                                        //  get distance to next anchor point
         if (dx < 0.01) return 0;                                                //  x-value not increasing, forbid
         dy = sd->apy[spc][ap+1] - myval;
         dist = sqrtf(dx * dx + dy * dy);
         if (dist < minx) return 0;                                              //  too close, forbid
      }
      if (ap > 0) {                                                              //  not the first anchor point
         dx = mxval - sd->apx[spc][ap-1];                                        //  get distance to prior anchor point
         if (dx < 0.01) return 0;                                                //  x-value not increasing, forbid
         dy = myval - sd->apy[spc][ap-1];
         dist = sqrtf(dx * dx + dy * dy);
         if (dist < minx) return 0;                                              //  too close, forbid
      }

      apset = 1;                                                                 //  mxval/myval = new node position
   }

   else                                                                          //  mouse click or new drag begin
   {
      minspc = minap = -1;                                                       //  find closest curve/anchor point
      mindist2 = 999999;

      for (spc = 0; spc < sd->Nspc; spc++)                                       //  loop curves
      {
         if (! sd->fact[spc]) continue;                                          //  not active

         if (sd->vert[spc]) {
            mxval = 1.0 * my / hh;                                               //  mouse position in curve space
            myval = 1.0 * mx / ww;
         }
         else {
            mxval = 1.0 * mx / ww;
            myval = 1.0 * (hh - my) / hh;
         }

         for (ap = 0; ap < sd->nap[spc]; ap++)                                   //  loop anchor points
         {
            cxval = sd->apx[spc][ap];
            cyval = sd->apy[spc][ap];
            dist2 = (mxval-cxval)*(mxval-cxval)
                  + (myval-cyval)*(myval-cyval);
            if (dist2 < mindist2) {
               mindist2 = dist2;                                                 //  remember closest anchor point
               minspc = spc;
               minap = ap;
            }
         }
      }

      if (minspc < 0) return 0;                                                  //  impossible
      spc = minspc;                                                              //  nearest curve
      ap = minap;                                                                //  nearest anchor point
   }

   if (evtype == GDK_BUTTON_PRESS && button == 3)                                //  right click, remove anchor point
   {
      if (sqrtf(mindist2) > minx) return 0;                                      //  not close enough
      if (sd->nap[spc] < 3) return 0;                                            //  < 2 anchor points would remain
      sd->nap[spc]--;                                                            //  decr. before loop
      for (kk = ap; kk < sd->nap[spc]; kk++) {
         sd->apx[spc][kk] = sd->apx[spc][kk+1];
         sd->apy[spc][kk] = sd->apy[spc][kk+1];
      }
      splcurve_generate(sd,spc);                                                 //  regenerate data for modified curve
      gtk_widget_queue_draw(sd->drawarea);
      sd->spcfunc(spc);                                                          //  call user function
      return 0;
   }

   if (! Fdrag)                                                                  //  new drag or left click
   {
      if (sd->vert[spc]) {
         mxval = 1.0 * my / hh;                                                  //  mouse position in curve space
         myval = 1.0 * mx / ww;
      }
      else {
         mxval = 1.0 * mx / ww;
         myval = 1.0 * (hh - my) / hh;
      }

      if (sqrtf(mindist2) < minx)                                                //  anchor point close enough,
      {                                                                          //    move this one to mouse position
         if (ap < sd->nap[spc]-1) {                                              //  not the last anchor point
            dx = sd->apx[spc][ap+1] - mxval;                                     //  get distance to next anchor point
            if (dx < 0.01) return 0;                                             //  x-value not increasing, forbid
            dy = sd->apy[spc][ap+1] - myval;
            dist = sqrtf(dx * dx + dy * dy);
            if (dist < minx) return 0;                                           //  too close, forbid
         }
         if (ap > 0) {                                                           //  not the first anchor point
            dx = mxval - sd->apx[spc][ap-1];                                     //  get distance to prior anchor point
            if (dx < 0.01) return 0;                                             //  x-value not increasing, forbid
            dy = myval - sd->apy[spc][ap-1];
            dist = sqrtf(dx * dx + dy * dy);
            if (dist < minx) return 0;                                           //  too close, forbid
         }

         apset = 1;                                                              //  mxval/myval = new node position
      }

      else                                                                       //  none close, add new anchor point
      {
         minspc = -1;                                                            //  find closest curve to mouse
         mindist2 = 999999;

         for (spc = 0; spc < sd->Nspc; spc++)                                    //  loop curves
         {
            if (! sd->fact[spc]) continue;                                       //  not active

            if (sd->vert[spc]) {
               mxval = 1.0 * my / hh;                                            //  mouse position in curve space
               myval = 1.0 * mx / ww;
            }
            else {
               mxval = 1.0 * mx / ww;
               myval = 1.0 * (hh - my) / hh;
            }

            cyval = splcurve_yval(sd,spc,mxval);
            dist2 = fabsf(myval - cyval);
            if (dist2 < mindist2) {
               mindist2 = dist2;                                                 //  remember closest curve
               minspc = spc;
            }
         }

         if (minspc < 0) return 0;                                               //  impossible
         if (mindist2 > minx) return 0;                                          //  not close enough to any curve
         spc = minspc;

         if (sd->nap[spc] > 49) {
            zmessageACK(mainwin,"Exceed 50 anchor points");
            return 0;
         }

         if (sd->vert[spc]) {
            mxval = 1.0 * my / hh;                                               //  mouse position in curve space
            myval = 1.0 * mx / ww;
         }
         else {
            mxval = 1.0 * mx / ww;
            myval = 1.0 * (hh - my) / hh;
         }

         for (ap = 0; ap < sd->nap[spc]; ap++)                                   //  find anchor point with next higher x
            if (mxval <= sd->apx[spc][ap]) break;                                //    (ap may come out 0 or nap)

         if (ap < sd->nap[spc] && sd->apx[spc][ap] - mxval < minx)               //  disallow < minx from next
               return 0;                                                         //    or prior anchor point
         if (ap > 0 && mxval - sd->apx[spc][ap-1] < minx) return 0;

         for (kk = sd->nap[spc]; kk > ap; kk--) {                                //  make hole for new point
            sd->apx[spc][kk] = sd->apx[spc][kk-1];
            sd->apy[spc][kk] = sd->apy[spc][kk-1];
         }

         sd->nap[spc]++;                                                         //  up point count
         apset = 1;                                                              //  mxval/myval = new node position
      }
   }

   if (evtype == GDK_MOTION_NOTIFY) Fdrag = 1;                                   //  remember drag is underway

   if (apset)
   {
      sd->apx[spc][ap] = mxval;                                                  //  new or moved anchor point
      sd->apy[spc][ap] = myval;                                                  //    at mouse position

      splcurve_generate(sd,spc);                                                 //  regenerate data for modified curve
      if (sd->drawarea) gtk_widget_queue_draw(sd->drawarea);                     //  redraw graph
      if (sd->spcfunc) sd->spcfunc(spc);                                         //  call user function
   }

   return 0;
}


//  add a new anchor point to a curve
//  spc:     curve number
//  px, py:  node coordinates in the range 0-1

int splcurve_addnode(spldat *sd, int spc, float px, float py)
{
   int      ap, kk;
   float    minx = 0.01 * splcurve_minx;                                         //  % to absolute distance

   for (ap = 0; ap < sd->nap[spc]; ap++)                                         //  find anchor point with next higher x
      if (px <= sd->apx[spc][ap]) break;                                         //    (ap may come out 0 or nap)

   if (ap < sd->nap[spc] && sd->apx[spc][ap] - px < minx)                        //  disallow < minx from next
         return 0;                                                               //    or prior anchor point
   if (ap > 0 && px - sd->apx[spc][ap-1] < minx) return 0;

   for (kk = sd->nap[spc]; kk > ap; kk--) {                                      //  make hole for new point
      sd->apx[spc][kk] = sd->apx[spc][kk-1];
      sd->apy[spc][kk] = sd->apy[spc][kk-1];
   }

   sd->apx[spc][ap] = px;                                                        //  add node coordinates
   sd->apy[spc][ap] = py;

   sd->nap[spc]++;                                                               //  up point count
   return 1;
}


//  if height/width too small, make bigger

int splcurve_resize(GtkWidget *drawarea)
{
   int   ww, hh;
   gtk_widget_get_size_request(drawarea,&ww,&hh);
   if (hh < 50) gtk_widget_set_size_request(drawarea,ww,50);
   return 1;
}


//  for expose event or when a curve is changed
//  draw all curves based on current anchor points

int splcurve_draw(GtkWidget *drawarea, cairo_t *cr, spldat *sd)
{
   int         ww, hh, spc, ap;
   float       xval, yval, px, py, qx, qy;

   ww = gtk_widget_get_allocated_width(sd->drawarea);                            //  drawing area size
   hh = gtk_widget_get_allocated_height(sd->drawarea);
   if (ww < 50 || hh < 50) return 0;

   cairo_set_line_width(cr,1);
   cairo_set_source_rgb(cr,0.7,0.7,0.7);

   for (int ii = 0; ii < sd->Nscale; ii++)                                       //  draw y-scale lines if any
   {
      px = ww * sd->xscale[0][ii];
      py = hh - hh * sd->yscale[0][ii];
      qx = ww * sd->xscale[1][ii];
      qy = hh - hh * sd->yscale[1][ii];
      cairo_move_to(cr,px,py);
      cairo_line_to(cr,qx,qy);
   }
   cairo_stroke(cr);

   cairo_set_source_rgb(cr,0,0,0);

   for (spc = 0; spc < sd->Nspc; spc++)                                          //  loop all curves
   {
      if (! sd->fact[spc]) continue;                                             //  not active

      if (sd->vert[spc])                                                         //  vert. curve
      {
         for (py = 0; py < hh; py++)                                             //  generate all points for curve
         {
            xval = 1.0 * py / hh;
            yval = splcurve_yval(sd,spc,xval);
            px = ww * yval;
            if (py == 0) cairo_move_to(cr,px,py);
            cairo_line_to(cr,px,py);
         }
         cairo_stroke(cr);

         for (ap = 0; ap < sd->nap[spc]; ap++)                                   //  draw boxes at anchor points
         {
            xval = sd->apx[spc][ap];
            yval = sd->apy[spc][ap];
            px = ww * yval;
            py = hh * xval;
            cairo_rectangle(cr,px-2,py-2,4,4);
         }
         cairo_fill(cr);
      }
      else                                                                       //  horz. curve
      {
         for (px = 0; px < ww; px++)                                             //  generate all points for curve
         {
            xval = 1.0 * px / ww;
            yval = splcurve_yval(sd,spc,xval);
            py = hh - hh * yval;
            if (px == 0) cairo_move_to(cr,px,py);
            cairo_line_to(cr,px,py);
         }
         cairo_stroke(cr);

         for (ap = 0; ap < sd->nap[spc]; ap++)                                   //  draw boxes at anchor points
         {
            xval = sd->apx[spc][ap];
            yval = sd->apy[spc][ap];
            px = ww * xval;
            py = hh - hh * yval;
            cairo_rectangle(cr,px-2,py-2,4,4);
         }
         cairo_fill(cr);
      }
   }

   return 0;
}


//  generate all curve data points when anchor points are modified

int splcurve_generate(spldat *sd, int spc)
{
   int      kk, kklo, kkhi;
   float    xval, yvalx;

   spline1(sd->nap[spc],sd->apx[spc],sd->apy[spc]);                              //  compute curve fitting anchor points

   kklo = 1000 * sd->apx[spc][0] - 30;                                           //  xval range = anchor point range
   if (kklo < 0) kklo = 0;                                                       //    + 0.03 extra below/above
   kkhi = 1000 * sd->apx[spc][sd->nap[spc]-1] + 30;
   if (kkhi > 1000) kkhi = 1000;

   for (kk = 0; kk < 1000; kk++)                                                 //  generate all points for curve
   {
      xval = 0.001 * kk;                                                         //  remove anchor point limits
      yvalx = spline2(xval);
      if (yvalx < 0) yvalx = 0;                                                  //  yval < 0 not allowed, > 1 OK
      sd->yval[spc][kk] = yvalx;
   }

   sd->mod[spc] = 1;                                                             //  mark curve modified

   return 0;
}


//  Retrieve curve data using interpolation of saved table of values

float splcurve_yval(spldat *sd, int spc, float xval)
{
   int      ii;
   float    x1, x2, y1, y2, y3;

   if (xval <= 0) return sd->yval[spc][0];
   if (xval >= 0.999) return sd->yval[spc][999];

   x2 = 1000.0 * xval;
   ii = x2;
   x1 = ii;
   y1 = sd->yval[spc][ii];
   y2 = sd->yval[spc][ii+1];
   y3 = y1 + (y2 - y1) * (x2 - x1);
   return y3;
}


//  load curve data from a file
//  returns 0 if success, sd is initialized from file data
//  returns 1 if fail (invalid file data), sd not modified

int splcurve_load(spldat *sd, FILE *fid)
{
   ch          *pp, buff[300];
   int         nn, ii, jj, err, myfid = 0;
   int         Nspc, fact[10], vert[10], nap[10];
   float       apx[10][50], apy[10][50];

   pp = fgets_trim(buff,300,fid,1);
   if (! pp) goto fail;
   nn = sscanf(pp,"%d",&Nspc);                                                   //  no. of curves
   if (nn != 1) goto fail;
   if (Nspc < 1 || Nspc > 10) goto fail;
   if (Nspc != sd->Nspc) goto fail;

   for (ii = 0; ii < Nspc; ii++)                                                 //  loop each curve
   {
      pp = fgets_trim(buff,300,fid,1);
      if (! pp) goto fail;
      nn = sscanf(pp,"%d %d %d",&fact[ii],&vert[ii],&nap[ii]);                   //  active flag, vert flag, anchors
      if (nn != 3) goto fail;
      if (fact[ii] < 0 || fact[ii] > 1) goto fail;
      if (vert[ii] < 0 || vert[ii] > 1) goto fail;
      if (nap[ii] < 2 || nap[ii] > 50) goto fail;

      pp = fgets_trim(buff,300,fid,1);                                           //  anchor points: nnn/nnn nnn/nnn ...

      for (jj = 0; jj < nap[ii]; jj++)                                           //  anchor point values
      {
         pp = (ch *) substring(buff,"/ ",2*jj+1);
         if (! pp) goto fail;
         err = convSF(pp,apx[ii][jj],0,1);
         if (err) goto fail;
         pp = (ch *) substring(buff,"/ ",2*jj+2);
         if (! pp) goto fail;
         err = convSF(pp,apy[ii][jj],0,1);
         if (err) goto fail;
      }
   }

   if (myfid) fclose(fid);

   sd->Nspc = Nspc;                                                              //  copy curve data to caller's arg

   for (ii = 0; ii < Nspc; ii++)
   {
      sd->fact[ii] = fact[ii];
      sd->vert[ii] = vert[ii];
      sd->nap[ii] = nap[ii];

      for (jj = 0; jj < nap[ii]; jj++)
      {
         sd->apx[ii][jj] = apx[ii][jj];
         sd->apy[ii][jj] = apy[ii][jj];
      }
   }

   for (ii = 0; ii < Nspc; ii++)                                                 //  generate curve data from anchor points
      splcurve_generate(sd,ii);

   if (sd->drawarea)                                                             //  redraw all curves
      gtk_widget_queue_draw(sd->drawarea);

   return 0;                                                                     //  success

fail:
   if (fid && myfid) fclose(fid);
   zmessageACK(mainwin,"curve file is invalid");
   return 1;
}


//  save curve data to a file

int splcurve_save(spldat *sd, FILE *fid)
{
   int         ii, jj, myfid = 0;

   fprintf(fid,"%d \n",sd->Nspc);                                                //  no. of curves

   for (ii = 0; ii < sd->Nspc; ii++)                                             //  loop each curve
   {
      fprintf(fid,"%d %d %d \n",sd->fact[ii],sd->vert[ii],sd->nap[ii]);          //  active flag, vert flag, anchors
      for (jj = 0; jj < sd->nap[ii]; jj++)                                       //  anchor point values
         fprintf(fid,"%.4f/%.4f  ",sd->apx[ii][jj],sd->apy[ii][jj]);
      fprintf(fid,"\n");
   }

   if (myfid) fclose(fid);
   return 0;
}


/********************************************************************************
   simplified GTK dialog functions

   create a dialog with response buttons (OK, cancel ...)
   add widgets to dialog (button, text entry, combo box ...)
   put data into widgets (text or numeric data)
   run the dialog, get user inputs (button press, text entry, checkbox selection ...)
   run caller event function when widgets change from user inputs
   run caller event function when dialog is completed or canceled
   get dialog completion status (OK, cancel, destroyed ...)
   get data from dialog widgets (the user inputs)
   destroy the dialog and free memory

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


//  private functions for widget events and dialog completion

int  zdialog_widget_event(GtkWidget *, zdialog *zd);
int  zdialog_delete_event(GtkWidget *, GdkEvent *, zdialog *zd);
int  zdialog_zspin_event(GtkWidget *, GdkEvent *, zdialog *zd);                  //  "zspin" widget

//  create a new zdialog dialog
//  The title and parent arguments may be null.
//  optional arguments: up to zdmaxbutts button labels followed by null
//  returned dialog status: +N = button N (1 to zdmaxbutts)
//                          <0 = [x] button or other GTK destroy action
//  completion buttons are also events like other widgets
//  all dialogs run parallel, use zdialog_wait() if needed
//  The status returned by zdialog_wait() corresponds to the button
//  (1-10) used to end the dialog. Status < 0 indicates the [x] button
//  was used or the dialog was killed by the program itself.

zdialog * zdialog_new(ch *title, GtkWidget *parent, ...)                         //  parent added
{
   zdialog        *zd;
   GtkWidget      *dialog, *hbox, *vbox, *butt, *hsep;
   ch             *bulab[zdmaxbutts];
   int            cc, ii, nbu;
   va_list        arglist;
   static int     uniqueID = 1;

   if (! main_thread()) zappcrash("zdialog_new() called from thread");

   va_start(arglist,parent);
   for (nbu = 0; nbu < zdmaxbutts; nbu++) {                                      //  get completion buttons
      bulab[nbu] = va_arg(arglist, ch *);
      if (! bulab[nbu] || bulab[nbu] == (ch *) 0x100000000) break;               //  ARM bug
   }
   va_end(arglist);

   if (! title) title = "";

   dialog = gtk_window_new(GTK_WINDOW_TOPLEVEL);
   gtk_window_set_title(GTK_WINDOW(dialog),title);
   vbox = gtk_box_new(VERTICAL,0);                                               //  vertical packing box
   gtk_container_add(GTK_CONTAINER(dialog),vbox);                                //  add to main window
   gtk_window_set_default_size(GTK_WINDOW(dialog),10,10);                        //  stop auto width of 150 pixels

   if (parent)
      gtk_window_set_transient_for(GTK_WINDOW(dialog),GTK_WINDOW(parent));

   gtk_box_set_spacing(GTK_BOX(vbox),2);
   gtk_container_set_border_width(GTK_CONTAINER(vbox),5);

   cc = sizeof(zdialog);                                                         //  allocate zdialog
   zd = (zdialog *) zmalloc(cc,"zdialog");

   if (zdialog_count == zdialog_max) {                                           //  add to active list
      for (ii = 0; ii < zdialog_count; ii++)
         Plog(0,"dialog: %s \n",zdialog_list[ii]->widget[0].data);
      zappcrash("max. zdialogs exceeded");
   }

   zdialog_list[zdialog_count] = zd;
   zdialog_count++;

   if (nbu) {                                                                    //  completion buttons
      hbox = gtk_box_new(HORIZONTAL,2);                                          //  add hbox for buttons at bottom
      gtk_box_pack_end(GTK_BOX(vbox),hbox,0,0,2);
      hsep = gtk_separator_new(HORIZONTAL);                                      //  add separator line
      gtk_box_pack_end(GTK_BOX(vbox),hsep,0,0,5);

      for (ii = nbu-1; ii >= 0; ii--) {                                          //  add buttons to hbox
         butt = gtk_button_new_with_label(bulab[ii]);                            //  reverse order nbu-1...0
         gtk_box_pack_end(GTK_BOX(hbox),butt,0,0,2);
         G_SIGNAL(butt,"clicked",zdialog_widget_event,zd);                       //  connect to event function
         zd->compwidget[ii] = butt;                                              //  save button widgets
         zd->compbutton[ii] = bulab[ii];                                         //  and button labels
      }
   }

   zd->compbutton[nbu] = 0;                                                      //  mark EOL

   zd->dialog = dialog;                                                          //  dialog window
   zd->title = zstrdup(title,"zdialog");                                         //  dialog title
   zd->parent = parent;                                                          //  parent window
   zd->sentinel1 = zdsentinel | (lrandz() & 0x0000FFFF);                         //  validity sentinels
   zd->sentinel2 = zd->sentinel1;                                                //  fixed part + random part
   zd->uniqueID = uniqueID++;                                                    //  increment unique ID
   zd->eventCB = 0;                                                              //  no user event callback function
   zd->zstat = 0;                                                                //  no zdialog status
   zd->disabled = 1;                                                             //  widget signals disabled
   zd->saveposn = 0;                                                             //  position not saved

   zd->widget[0].wname = "dialog";                                               //  set up 1st widget = dialog
   zd->widget[0].type = "dialog";
   zd->widget[0].pname = 0;                                                      //  no parent
   zd->widget[0].data = zstrdup(title,"zdialog");
   zd->widget[0].widget = dialog;
   zd->widget[1].type = 0;                                                       //  eof - no contained widgets yet

   return zd;
}


//  change a zdialog title

void zdialog_set_title(zdialog *zd, ch *title)
{
   gtk_window_set_title(GTK_WINDOW(zd->widget[0].widget),title);
   return;
}


//  set a zdialog to be modal

void zdialog_set_modal(zdialog *zd)
{
   GtkWidget  *widget = zdialog_gtkwidget(zd,"dialog");
   gtk_window_set_modal(GTK_WINDOW(widget),1);
   gtk_window_set_keep_above(GTK_WINDOW(widget),1);
   return;
}


//  set a zdialog to be decorated or not

void zdialog_set_decorated(zdialog *zd, int decorated)
{
   void zdialog_drag(GtkWidget *widget, GdkEventButton *event, void *);

   GtkWidget  *widget;

   widget = zdialog_gtkwidget(zd,"dialog");
   gtk_window_set_decorated(GTK_WINDOW(widget),decorated);
   if (decorated) return;
   gtk_widget_add_events(widget,GDK_BUTTON_PRESS_MASK);
   gtk_widget_add_events(widget,GDK_BUTTON_RELEASE_MASK);
   gtk_widget_add_events(widget,GDK_POINTER_MOTION_MASK);
   G_SIGNAL(widget,"button-press-event",zdialog_drag,0);                         //  connect mouse events to drag
   G_SIGNAL(widget,"button-release-event",zdialog_drag,0);                       //    undecorated window
   G_SIGNAL(widget,"motion-notify-event",zdialog_drag,0);
   return;
}

void zdialog_drag(GtkWidget *widget, GdkEventButton *event, void *)
{
   static int  bdown = 0, type;
   static int  mx0, my0, mx, my;
   static int  wx0, wy0, wx, wy;

   type = event->type;
   gdk_device_get_position(zfuncs::mouse,0,&mx,&my);                             //  mouse position in monitor

   if (type == GDK_BUTTON_PRESS) {
      bdown = 1;
      mx0 = mx;                                                                  //  drag start
      my0 = my;
      gtk_window_get_position(GTK_WINDOW(widget),&wx0,&wy0);                     //  initial window position
   }

   if (type == GDK_BUTTON_RELEASE)
      bdown = 0;

   if (type == GDK_MOTION_NOTIFY) {
      if (! bdown) return;
      wx = wx0 + mx - mx0;
      wy = wy0 + my - my0;
      gtk_window_move(GTK_WINDOW(widget),wx,wy);
   }

   return;
}


//  present a zdialog (visible and on top)

void zdialog_present(zdialog *zd)
{
   zmainsleep(0.1);
   if (! zdialog_valid2(zd)) return;
   gtk_window_present(GTK_WINDOW(zd->dialog));
   return;
}


//  set zdialog can or can not receive focus (informational or report dialog)

void zdialog_can_focus(zdialog *zd, int Fcan)
{
   gtk_window_set_accept_focus(GTK_WINDOW(zd->dialog),Fcan);
   return;
}


//  set focus on dialog window or window and named widget
//  (widget name may be null or missing)
//  see also: gtk_window_activate_focus(GtkWindow *)

void zdialog_set_focus(zdialog *zd, ch *wname)
{
   GtkWindow   *window;
   GtkWidget   *widget;

   window = GTK_WINDOW(zd->dialog);
   if (wname) widget = zdialog_gtkwidget(zd,wname);
   else widget = 0;

   if (wname) gtk_window_set_focus(window,widget);
   else gtk_window_activate_focus(window);
   return;
}


//  add widget to existing zdialog
//
//   Arguments after parent are optional and default to 0.
//   zd         zdialog *, created with zdialog_new()
//   type       string, one of the widget types listed below
//   wname      string, widget name, used to stuff or fetch widget data
//   parent     string, parent name: "dialog" or a previously added container widget
//   data       string, initial data for widget (label name, entry string, spin value, etc.)
//   size       cc for text entry or pixel size for image widget
//   homog      for hbox or vbox to make even space allocation for contained widgets
//   expand     widget should expand with dialog box expansion
//   space      extra space between this widget and neighbors, pixels
//   wrap       allow text to wrap at right margin
//
//   data can be a string ("initial widget data") or a number in string form ("12.345")
//   data for togbutt / check / radio: use "0" or "1" for OFF or ON
//   data for spin / zspin / hscale / vscale: use "min|max|step|value" (default: 0 | 100 | 1 | 50)
//   data for colorbutt: use "rrr|ggg|bbb" with values 0-255 for each RGB color.
//   This format is used to initialize the control and read back when user selects a color.
//   Multiple radio buttons with same parent are a group: pressing one turns the others OFF.

int zdialog_add_widget_long (
     zdialog *zd, ch *type, ch *wname, ch *pname,                                //  mandatory args
     ch *data, int size, int homog, int expand, int space, int wrap)             //  optional args (default = 0)
{
   int textview_focus_in_event(GtkWidget *widget);                               //  for popup_text insertion
   int zdialog_activate_event(GtkWidget *, zdialog *zd);

   GtkWidget      *widget = 0, *pwidget = 0, *fwidget = 0;
   GtkWidget      *image, *vbox;
   GtkTextBuffer  *editBuff = 0;
   PIXBUF         *pixbuf = 0;
   GdkRGBA        gdkrgba;
   GError         *gerror = 0;
   ch             *pp, *ptype = 0;
   ch             vdata[30], iconpath[200];
   double         min, max, step, val;
   double         f256 = 1.0 / 256.0;
   int            iiw, iip, kk, err;

   if (! zdialog_valid(zd)) zappcrash("zdialog invalid");

   for (iiw = 1; zd->widget[iiw].type; iiw++);                                   //  find next avail. slot
   if (iiw > zdmaxwidgets-2) zappcrash("too many widgets: %d",iiw);

   zd->widget[iiw].type = zstrdup(type,"zdialog");                               //  initz. widget struct
   zd->widget[iiw].wname = zstrdup(wname,"zdialog");
   zd->widget[iiw].pname = zstrdup(pname,"zdialog");
   zd->widget[iiw].data = 0;
   zd->widget[iiw].size = size;
   zd->widget[iiw].homog = homog;
   zd->widget[iiw].expand = expand;
   zd->widget[iiw].space = space;
   zd->widget[iiw].wrap = wrap;
   zd->widget[iiw].widget = 0;

   zd->widget[iiw+1].type = 0;                                                   //  set new EOF marker

   if (strmatchV(type,"dialog","hbox","vbox","hsep","vsep","frame","scrwin",
                      "label","link","entry","zentry","zedit","text","report",
                      "button","zbutton","togbutt","check","radio",
                      "imagebutt","colorbutt","combo","spin","zspin",
                      "hscale","hscale2","vscale","icon","image",null) == 0) {
      Plog(0,"zdialog, bad widget type: %s \n",type);
      return 0;
   }

   for (iip = iiw-1; iip >= 0; iip--)                                            //  find parent (container) widget
      if (strmatch(pname,zd->widget[iip].wname)) break;
   if (iip < 0) zappcrash("zdialog, no parent for widget: %s",wname);

   pwidget = zd->widget[iip].widget;                                             //  parent widget, type
   ptype = zd->widget[iip].type;

   if (strmatchV(ptype,"dialog","hbox","vbox","frame","scrwin",null) == 0)
      zappcrash("zdialog, bad widget parent type: %s",ptype);

   if (strmatch(type,"hbox")) widget = gtk_box_new(HORIZONTAL,space);            //  expandable container boxes
   if (strmatch(type,"vbox")) widget = gtk_box_new(VERTICAL,space);
   if (strstr("hbox vbox",type))
      gtk_box_set_homogeneous(GTK_BOX(widget),homog);

   if (strmatch(type,"hsep")) widget = gtk_separator_new(HORIZONTAL);            //  horiz. & vert. separators
   if (strmatch(type,"vsep")) widget = gtk_separator_new(VERTICAL);

   if (strmatch(type,"frame")) {                                                 //  frame around contained widgets
      widget = gtk_frame_new(data);
      gtk_frame_set_shadow_type(GTK_FRAME(widget),GTK_SHADOW_IN);
      data = 0;
   }

   if (strmatch(type,"scrwin")) {                                                //  scrolled window container
      widget = gtk_scrolled_window_new(0,0);
      gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(widget),
                        GTK_POLICY_AUTOMATIC,GTK_POLICY_AUTOMATIC);
      gtk_scrolled_window_set_overlay_scrolling(GTK_SCROLLED_WINDOW(widget),0);
      data = 0;
   }

   if (strmatch(type,"label")) {                                                 //  label (static text)
      widget = gtk_label_new(data);
      if (size) gtk_label_set_width_chars(GTK_LABEL(widget),size);
      if (data && strstr(data,"<span"))
         gtk_label_set_markup(GTK_LABEL(widget),data);
      data = 0;
   }

   if (strmatch(type,"link")) {                                                  //  label is clickable
      if (strmatch(wname,"nolabel"))
         widget = gtk_link_button_new(data);                                     //  link is also label
      else
         widget = gtk_link_button_new_with_label(data,wname);                    //  label >> link
      G_SIGNAL(widget,"clicked",zdialog_widget_event,zd);
      data = 0;
   }

   if (strmatch(type,"entry")) {                                                 //  text input, single line
      widget = gtk_entry_new();
      if (data) gtk_entry_set_text(GTK_ENTRY(widget),data);
      if (size) gtk_entry_set_width_chars(GTK_ENTRY(widget),size);
      G_SIGNAL(widget,"changed",zdialog_widget_event,zd);
      G_SIGNAL(widget,"activate",zdialog_activate_event,zd);
   }

   if (strmatch(type,"zentry")) {                                                //  text input, single line
      widget = gtk_text_view_new();
      gtk_text_view_set_top_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_bottom_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_left_margin(GTK_TEXT_VIEW(widget),5);
      if (! size) size = 10;                                                     //  scale widget for font size
      gtk_widget_set_size_request(widget,size*appfontsize,2*appfontsize);
      gtk_text_view_set_editable(GTK_TEXT_VIEW(widget),1);
      gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget),GTK_WRAP_NONE);          //  this does nothing    GTK bug
      gtk_text_view_set_accepts_tab(GTK_TEXT_VIEW(widget),0);
      editBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      if (data) gtk_text_buffer_set_text(editBuff,data,-1);
      G_SIGNAL(editBuff,"changed",zdialog_widget_event,zd);                      //  buffer signals, not widget
      G_SIGNAL(widget,"focus-in-event",textview_focus_in_event,widget);          //  for popup_text inserts
   }

   if (strmatch(type,"zedit")) {                                                 //  text input, opt. multi-line
      widget = gtk_text_view_new();
      gtk_text_view_set_top_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_bottom_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_left_margin(GTK_TEXT_VIEW(widget),5);
      if (! size) size = 10;                                                     //  scale widget for font size
      gtk_widget_set_size_request(widget,size*appfontsize,2*appfontsize);
      gtk_text_view_set_editable(GTK_TEXT_VIEW(widget),1);
      if (wrap) gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget),GTK_WRAP_WORD);
      gtk_text_view_set_accepts_tab(GTK_TEXT_VIEW(widget),0);
      editBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      if (data) gtk_text_buffer_set_text(editBuff,data,-1);
      G_SIGNAL(editBuff,"changed",zdialog_widget_event,zd);                      //  buffer signals, not widget
      G_SIGNAL(widget,"focus-in-event",textview_focus_in_event,widget);          //  for popup_text inserts
   }

   if (strmatch(type,"text") || strmatch(type,"report")) {                       //  text output (not editable)
      widget = gtk_text_view_new();
      gtk_text_view_set_top_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_bottom_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_left_margin(GTK_TEXT_VIEW(widget),5);
      if (wrap) gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget),GTK_WRAP_WORD);
      editBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      if (data) gtk_text_buffer_set_text(editBuff,data,-1);
      gtk_text_view_set_editable(GTK_TEXT_VIEW(widget),0);
      gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(widget),0);
      if (strmatch(type,"text")) gtk_widget_set_can_focus(widget,0);             //  inactivate KB navi keys
      type = "text";
   }

   if (strmatch(type,"button")) {                                                //  button
      widget = gtk_button_new_with_label(data);
      G_SIGNAL(widget,"clicked",zdialog_widget_event,zd);
      data = 0;
   }

   if (strmatch(type,"zbutton")) {                                               //  checkbox used as small button
      if (data) widget = gtk_check_button_new_with_label(data);
      else  widget = gtk_check_button_new();
      G_SIGNAL(widget,"toggled",zdialog_widget_event,zd);
      data = "0";                                                                //  default data
   }

   if (strmatch(type,"togbutt")) {                                               //  toggle button
      widget = gtk_toggle_button_new_with_label(data);
      G_SIGNAL(widget,"toggled",zdialog_widget_event,zd);
      data = "0";                                                                //  default data
   }

   if (strmatch(type,"imagebutt")) {                                             //  button with image
      snprintf(iconpath,200,"%s/%s",get_zimagedir(),data);
      data = 0;
      pixbuf = gdk_pixbuf_new_from_file_at_scale(iconpath,size,size,1,&gerror);
      if (pixbuf) {
         image = gtk_image_new_from_pixbuf(pixbuf);
         g_object_unref(pixbuf);
      }
      else image = gtk_image_new_from_icon_name("missing",GTK_ICON_SIZE_BUTTON);
      widget = gtk_button_new_with_label(data);
      gtk_button_set_image(GTK_BUTTON(widget),image);
      G_SIGNAL(widget,"clicked",zdialog_widget_event,zd);
   }

   if (strmatch(type,"colorbutt")) {                                             //  color edit button
      if (! data) data = "0|0|0";                                                //  data format: "nnn|nnn|nnn" = RGB
      pp = substring(data,'|',1); gdkrgba.red = f256 * atoi(pp);                 //  RGB values are 0-1
      pp = substring(data,'|',2); gdkrgba.green = f256 * atoi(pp);
      pp = substring(data,'|',3); gdkrgba.blue = f256 * atoi(pp);
      gdkrgba.alpha = 1.0;
      widget = gtk_color_button_new_with_rgba(&gdkrgba);
      G_SIGNAL(widget,"color-set",zdialog_widget_event,zd);
   }

   if (strmatch(type,"check")) {                                                 //  checkbox
      if (data) widget = gtk_check_button_new_with_label(data);
      else  widget = gtk_check_button_new();
      G_SIGNAL(widget,"toggled",zdialog_widget_event,zd);
      data = "0";                                                                //  default data
   }

   if (strmatch(type,"combo")) {                                                 //  combo box
      widget = gtk_combo_box_text_new();
      if (! size) size = 10;                                                     //  scale widget for font size
      gtk_widget_set_size_request(widget,size*appfontsize,2*appfontsize);
      G_SIGNAL(widget,"changed",zdialog_widget_event,zd);
      G_SIGNAL(widget,"popdown",zdialog_widget_event,zd);                        //  fails for wayland
   }

   if (strmatch(type,"radio")) {                                                 //  radio button
      for (kk = iip+1; kk <= iiw; kk++)
         if (strmatch(zd->widget[kk].pname,pname) &&                             //  find first radio button
             strmatch(zd->widget[kk].type,"radio")) break;                       //    with same container
      if (kk == iiw)
         widget = gtk_radio_button_new_with_label(null,data);                    //  this one is first
      else
         widget = gtk_radio_button_new_with_label_from_widget                    //  not first, add to group
              (GTK_RADIO_BUTTON(zd->widget[kk].widget),data);
      G_SIGNAL(widget,"toggled",zdialog_widget_event,zd);
      data = "0";                                                                //  default data
   }

   if (strmatchV(type,"spin","hscale","hscale2","vscale",null)) {                //  spin button or sliding scale
      if (! data) zappcrash("zdialog_add_widget(): data missing");               //  "min|max|step|value"
      pp = substring(data,'|',1); err = convSD(pp,min);
      pp = substring(data,'|',2); err += convSD(pp,max);
      pp = substring(data,'|',3); err += convSD(pp,step);
      pp = substring(data,'|',4); err += convSD(pp,val);
      if (err) zappcrash("zdialog_add_widget(): bad data: %s",data);

      zd->widget[iiw].lolim = min;
      zd->widget[iiw].hilim = max;
      zd->widget[iiw].step = step;

      if (strmatch(type,"spin")) {
         widget = gtk_spin_button_new_with_range(min,max,step);
         gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget),val);
      }
      if (strmatch(type,"hscale")) {
         widget = gtk_scale_new_with_range(HORIZONTAL,min,max,step);
         gtk_range_set_value(GTK_RANGE(widget),val);
         gtk_scale_set_draw_value(GTK_SCALE(widget),0);
         gtk_scale_set_has_origin(GTK_SCALE(widget),0);
      }
      if (strmatch(type,"hscale2")) {                                            //  add digital value on the right
         widget = gtk_scale_new_with_range(HORIZONTAL,min,max,step);
         gtk_range_set_value(GTK_RANGE(widget),val);
         gtk_scale_set_draw_value(GTK_SCALE(widget),1);
         gtk_scale_set_value_pos(GTK_SCALE(widget),GTK_POS_RIGHT);
         gtk_scale_set_has_origin(GTK_SCALE(widget),0);
      }
      if (strmatch(type,"vscale")) {
         widget = gtk_scale_new_with_range(VERTICAL,min,max,step);
         gtk_range_set_value(GTK_RANGE(widget),val);
         gtk_scale_set_draw_value(GTK_SCALE(widget),0);
      }

      G_SIGNAL(widget,"value-changed",zdialog_widget_event,zd);
      snprintf(vdata,30,"%g",val);
      data = vdata;
   }

   if (strmatch(type,"zspin")) {                                                 //  "zspin" widget with range
      if (! data) zappcrash("zdialog_add_widget(): data missing");               //  "min|max|step|value"
      pp = substring(data,'|',1); err = convSD(pp,min);
      pp = substring(data,'|',2); err += convSD(pp,max);
      pp = substring(data,'|',3); err += convSD(pp,step);
      pp = substring(data,'|',4); err += convSD(pp,val);
      if (err) zappcrash("zdialog_add_widget(): bad data: %s",data);

      zd->widget[iiw].lolim = min;
      zd->widget[iiw].hilim = max;
      zd->widget[iiw].step = step;
      err = convDS(val,7,vdata);                                                 //  initial value >> text
      data = vdata;
      widget = gtk_text_view_new();                                              //  GTK widget is text_view
      gtk_text_view_set_top_margin(GTK_TEXT_VIEW(widget),2);
      gtk_text_view_set_left_margin(GTK_TEXT_VIEW(widget),5);
      if (! size) size = 5;                                                      //  scale widget for font size
      gtk_widget_set_size_request(widget,size*appfontsize,2*appfontsize);
      gtk_text_view_set_editable(GTK_TEXT_VIEW(widget),1);
      gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget),GTK_WRAP_NONE);
      gtk_text_view_set_accepts_tab(GTK_TEXT_VIEW(widget),0);
      gtk_text_view_set_input_purpose(GTK_TEXT_VIEW(widget),GTK_INPUT_PURPOSE_NUMBER);
      editBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      gtk_text_buffer_set_text(editBuff,data,-1);
      gtk_widget_add_events(widget,GDK_SCROLL_MASK);
      gtk_widget_add_events(widget,GDK_FOCUS_CHANGE_MASK);
      G_SIGNAL(editBuff,"changed",zdialog_zspin_event,zd);                       //  buffer signals, not widget
      G_SIGNAL(widget,"key-press-event",zdialog_zspin_event,zd);
      G_SIGNAL(widget,"focus-out-event",zdialog_zspin_event,zd);
      G_SIGNAL(widget,"scroll-event",zdialog_zspin_event,zd);
   }

   if (strmatch(type,"icon")) {                                                  //  image widget from icon
      snprintf(iconpath,200,"%s/%s",get_zimagedir(),data);
      data = 0;                                                                  //  data not further used
      pixbuf = gdk_pixbuf_new_from_file_at_scale(iconpath,size,size,1,&gerror);
      if (pixbuf) {
         widget = gtk_image_new_from_pixbuf(pixbuf);
         g_object_unref(pixbuf);
      }
      else widget = gtk_image_new_from_icon_name("missing",GTK_ICON_SIZE_BUTTON);
   }

   if (strmatch(type,"image"))                                                   //  image widget from pixbuf
      widget = gtk_image_new_from_pixbuf((GdkPixbuf *) data);                    //  use (ch *) pixbuf in call

   //  all widget types come here

   zd->widget[iiw].widget = widget;                                              //  set widget in zdialog

   if (strmatchV(type,"zentry","zspin","zedit","text","scrwin",0)) {             //  add frame around these widgets        24.30
      if (! strmatch(ptype,"scrwin")) {                                          //    unless parent is scroll widget
         fwidget = gtk_frame_new(0);
         gtk_frame_set_shadow_type(GTK_FRAME(fwidget),GTK_SHADOW_IN);
         gtk_container_add(GTK_CONTAINER(fwidget),widget);
         widget = fwidget;
      }
   }

   if (strmatch(ptype,"hbox") || strmatch(ptype,"vbox"))                         //  add to hbox/vbox
      gtk_box_pack_start(GTK_BOX(pwidget),widget,expand,expand,space);
   if (strmatch(ptype,"frame"))                                                  //  add to frame
      gtk_container_add(GTK_CONTAINER(pwidget),widget);
   if (strmatch(ptype,"scrwin"))                                                 //  add to scroll window
      gtk_container_add(GTK_CONTAINER(pwidget),widget);
   if (strmatch(ptype,"dialog")) {                                               //  add to dialog box
      vbox = gtk_bin_get_child(GTK_BIN(pwidget));                                //  dialog is a gtkwindow
      gtk_box_pack_start(GTK_BOX(vbox),widget,expand,expand,space);
   }
   if (data) zd->widget[iiw].data = zstrdup(data,"zdialog");                     //  widget memory

   return 0;
}


//  add widget to existing zdialog - alternative form (clearer and easier code)
//  options: "size=nn | homog | expand | space=nn | wrap"  (all optional, any order)

int zdialog_add_widget(zdialog *zd, ch *type, ch *wname, ch *parent, ch *data, ch *options)
{
   int      size = 0, homog = 0, expand = 0, space = 0, wrap = 0;
   ch       *pp, *param;
   int      stat, Nth, pval = 0;

   if (! options) options = "";

   for (Nth = 1; true; Nth++)
   {
      param = substring(options,"|",Nth);                                        //  get pname=value
      if (! param) break;
      pp = strchr(param,'=');
      if (pp) pval = atoi(pp+1);
      if (strstr(param,"size")) size = pval;
      else if (strstr(param,"homog")) homog = 1;
      else if (strstr(param,"expand")) expand = 1;
      else if (strstr(param,"space")) space = pval;
      else if (strstr(param,"wrap")) wrap = 1;
      else zappcrash("bad zdialog options: %s",options);
   }

//   printf("zdialog_add_widget_long(type %s  wname %s  data %s  size %d  homog %d  expand %d  space %d  wrap %d \n",
//                                     type, wname, data, size, homog, expand, space, wrap);

   stat = zdialog_add_widget_long(zd,type,wname,parent,data,size,homog,expand,space,wrap);
   return stat;
}


//  return 1/0 if zdialog is valid/invalid

int zdialog_valid(zdialog *zd, ch *title)                                        //  title is optional
{
   int      ok, ii;

   if (! zd) return 0;

   for (ii = 0; ii < zdialog_count; ii++)                                        //  find in valid zdialog list
      if (zd == zdialog_list[ii]) break;
   if (ii == zdialog_count) {
      Plog(0,"*** zdialog invalid %s \n",title);
      return 0;
   }

   ok = 1;
   if ((zd->sentinel1 & 0xFFFF0000) != zdsentinel) ok = 0;
   if (zd->sentinel2 != zd->sentinel1) ok = 0;
   if (! ok) {
      Plog(0,"*** zdialog sentinel invalid %s \n",title);
      return 0;
   }

   if (title && ! strmatch(title,zd->title)) {
      Plog(0,"*** zdialog title invalid %s \n",title);
      return 0;
   }

   return 1;
}


//  return 1/0 if zdialog is valid/invalid
//  silent version to use when zdialog is possibly destroyed

int zdialog_valid2(zdialog *zd, ch *title)
{
   int      ok, ii;
   
   if (! zd) return 0;                                                           //  24.20

   for (ii = 0; ii < zdialog_count; ii++)
      if (zd == zdialog_list[ii]) break;
   if (ii == zdialog_count) return 0;

   ok = 1;
   if ((zd->sentinel1 & 0xFFFF0000) != zdsentinel) ok = 0;
   if (zd->sentinel2 != zd->sentinel1) ok = 0;
   if (! ok) return 0;

   if (title && ! strmatch(title,zd->title)) return 0;

   return 1;
}


//  find zdialog widget from zdialog and widget name

int zdialog_find_widget(zdialog *zd, ch *wname)
{
   if (! zdialog_valid(zd)) {
      Plog(0,"invalid zdialog %p \n",zd);
      return 0;
   }

   for (int ii = 0; zd->widget[ii].type; ii++)
      if (strmatch(zd->widget[ii].wname,wname)) return ii;

   Plog(0,"zdialog bad widget name: %s \n",wname);
   return 0;
}


//  get GTK widget from zdialog and widget name

GtkWidget * zdialog_gtkwidget(zdialog *zd, ch *wname)
{
   if (strmatch(wname,"dialog")) return zd->widget[0].widget;
   int ii = zdialog_find_widget(zd,wname);
   if (ii) return zd->widget[ii].widget;
   return 0;
}


//  set an "image" widget type from a GDK pixbuf
//  returns 0 if OK, else +N

int zdialog_set_image(zdialog *zd, ch *wname, GdkPixbuf *pixbuf)
{
   GtkWidget   *widget;
   int         ii;

   ii = zdialog_find_widget(zd,wname);
   if (! ii) return 2;
   if (! strmatch(zd->widget[ii].type,"image")) return 3;
   widget = zd->widget[ii].widget;
   gtk_image_set_from_pixbuf(GTK_IMAGE(widget),pixbuf);
   return 0;
}


//  add a popup tool tip to a zdialog widget

int zdialog_add_ttip(zdialog *zd, ch *wname, ch *ttip)
{
   GtkWidget   *widget;
   int         ii;

   if (! zdialog_valid(zd)) return 0;

   for (ii = 0; zd->compwidget[ii]; ii++)                                        //  search completion buttons
      if (strmatch(zd->compbutton[ii],wname)) {                                  //    for matching wname
         gtk_widget_set_tooltip_text(zd->compwidget[ii],ttip);
         return 1;
      }

   widget = zdialog_gtkwidget(zd,wname);                                         //  search zdialog widgets
   if (! widget) return 0;

   gtk_widget_set_tooltip_text(widget,ttip);
   return 1;
}


//  set a common group for a set of radio buttons
//  (GTK, this does not work)

int zdialog_set_group(zdialog *zd, ch *radio1, ...)
{
   va_list        arglist;
   ch             *radio2;
   GtkWidget      *gwidget, *widget;
   GSList         *glist;

   gwidget = zdialog_gtkwidget(zd,radio1);
   glist = gtk_radio_button_get_group(GTK_RADIO_BUTTON(gwidget));
   if (! glist) zappcrash("no radio button group");

   va_start(arglist,radio1);

   while (true)
   {
      radio2 = va_arg(arglist,ch *);
      if (! radio2 || radio2 == (ch *) 0x100000000) break;                       //  ARM bug
      widget = zdialog_gtkwidget(zd,radio2);
      gtk_radio_button_set_group(GTK_RADIO_BUTTON(widget),glist);
   }

   va_end(arglist);

   return 0;
}


//  resize dialog to a size greater than initial size
//  (as determined by the included widgets)

int zdialog_resize(zdialog *zd, int width, int height)
{
   if (! zdialog_valid(zd)) return 0;
   if (! width) width = 10;                                                      //  stop spurious GTK warnings
   if (! height) height = 10;
   GtkWidget *window = zd->widget[0].widget;
   gtk_window_set_default_size(GTK_WINDOW(window),width,height);
   return 1;
}


//  put data into a zdialog widget
//  private function

int zdialog_put_data(zdialog *zd, ch *wname, ch *data)
{
   GtkWidget      *widget;
   GtkTextBuffer  *textBuff;
   GdkRGBA        gdkrgba;
   int            iiw, nn, kk, err, Nsteps;
   ch             *type, *pp;
   ch             *wdata, sdata[32];
   double         dval;
   double         f256 = 1.0 / 256.0;
   double         lval, hval, nval, F, F2;
   double         fdata, lolim, hilim, step;                                     //  double

   iiw = zdialog_find_widget(zd,wname);
   if (! iiw) return 0;

   type = zd->widget[iiw].type;
   widget = zd->widget[iiw].widget;

   wdata = zd->widget[iiw].data;
   if (wdata) zfree(wdata);                                                      //  free prior data memory
   zd->widget[iiw].data = 0;

   if (data) {
      if (utf8_check(data)) wdata = zstrdup("bad UTF8 data","zdialog");          //  replace bad UTF-8 encoding
      else wdata = zstrdup(data,"zdialog");                                      //  set new data for widget
      zd->widget[iiw].data = wdata;
   }

   zd->disabled++;                                                               //  disable for widget stuffing

   if (strmatch(type,"label"))
      gtk_label_set_text(GTK_LABEL(widget),data);

   if (strmatch(type,"link"))
      gtk_label_set_text(GTK_LABEL(widget),data);

   if (strmatch(type,"entry"))
      gtk_entry_set_text(GTK_ENTRY(widget),data);

   if (strmatch(type,"zentry")) {                                                //  text input, single line
      textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      gtk_text_buffer_set_text(textBuff,data,-1);
   }

   if (strmatchV(type,"button","zbutton",null))                                  //  change button label
      gtk_button_set_label(GTK_BUTTON(widget),data);

   if (strmatch(type,"zedit")) {                                                 //  text input to editable text
      textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      gtk_text_buffer_set_text(textBuff,data,-1);
   }

   if (strmatch(type,"text")) {                                                  //  text output
      textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      gtk_text_buffer_set_text(textBuff,data,-1);
   }

   if (strmatchV(type,"togbutt","check","radio",null))
   {
      if (! data) kk = nn = 0;
      else kk = convSI(data,nn);
      if (kk != 0) nn = 0;                                                       //  data not integer, force zero
      if (nn <= 0) nn = 0; else nn = 1;
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget),nn);                //  set gtk widget value
   }

   if (strmatch(type,"spin")) {
      kk = convSD(data,dval);
      if (kk != 0) dval = 0.0;
      gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget),dval);
   }

   if (strmatch(type,"zspin")) {                                                 //  "zspin" widget
      lolim = zd->widget[iiw].lolim;
      hilim = zd->widget[iiw].hilim;
      step = zd->widget[iiw].step;
      err = convSD(data,fdata);                                                  //  string --> double
      if (err) goto retx;
      Nsteps = (fdata - lolim) / step + 0.5;                                     //  nearest exact step
      fdata = lolim + Nsteps * step;
      if (fdata < lolim) fdata = lolim;                                          //  enforce limits
      if (fdata > hilim) fdata = hilim;
      convDS(fdata,7,sdata);                                                     //  double --> string, precision 7
      textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
      gtk_text_buffer_set_text(textBuff,sdata,-1);
   }

   if (strmatch(type,"colorbutt")) {                                             //  color button data is nnn|nnn|nnn
      pp = substring(data,'|',1);
      if (pp) gdkrgba.red = f256 * atoi(pp);                                     //  RGB range is 0-1
      pp = substring(data,'|',2);
      if (pp) gdkrgba.green = f256 * atoi(pp);
      pp = substring(data,'|',3);
      if (pp) gdkrgba.blue = f256 * atoi(pp);
      gdkrgba.alpha = 1.0;
      gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(widget),&gdkrgba);
   }

   if (strmatchV(type,"hscale","hscale2","vscale",null))                         //  slider widget
   {
      kk = convSD(data,dval);                                                    //  zdialog widget value
      if (kk != 0) dval = 0.0;

      if (zd->widget[iiw].rescale)                                               //  widget value --> slider value
      {
         lval = zd->widget[iiw].lval;                                            //  rescaled for more sensitivity
         nval = zd->widget[iiw].nval;                                            //    around neutral value
         hval = zd->widget[iiw].hval;

         if (dval > lval && dval <= nval) {                                      //  if dval == lval or dval == hval
            F2 = (nval - dval) / (nval - lval);                                  //    then dval is not revised
            F = sqrtf(F2);
            dval = nval - F * (nval - lval);
         }

         else if (dval >= nval && dval < hval) {
            F2 = (dval - nval) / (hval - nval);
            F = sqrtf(F2);
            dval = nval + F * (hval - nval);
         }
      }

      gtk_range_set_value(GTK_RANGE(widget),dval);
   }

   if (strmatch(type,"combo"))                                                   //  combo box
   {
      if (blank_null(data))                                                      //  if blank, set no active entry
         gtk_combo_box_set_active(GTK_COMBO_BOX(widget),-1);
      else {
         if (! zd->widget[iiw].zlist)                                            //  add parallel zlist if not already
            zd->widget[iiw].zlist = zlist_new(0);
         nn = zlist_find(zd->widget[iiw].zlist,data,0);                          //  find matching zlist entry
         if (nn < 0) {
            zlist_append(zd->widget[iiw].zlist,data,0);                          //  not found, append new entry to zlist
            gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget),data);     //  append new entry to combo box
            nn = zlist_count(zd->widget[iiw].zlist) - 1;                         //  entry = count - 1
         }
         gtk_combo_box_set_active(GTK_COMBO_BOX(widget),nn);                     //  set combo box active entry
      }
   }

retx:
   zd->disabled--;                                                               //  re-enable dialog
   return iiw;
}


//  get data from a dialog widget based on its name
//  private function

ch * zdialog_get_data(zdialog *zd, ch *wname)
{
   int ii = zdialog_find_widget(zd,wname);
   if (ii) return zd->widget[ii].data;
   return 0;
}


//  set new limits for a numeric data entry widget (spin, zspin, hscale, vscale)

int zdialog_set_limits(zdialog *zd, ch *wname, double min, double max)
{
   GtkWidget   *widget;
   ch          *type;
   int         iiw;

   iiw = zdialog_find_widget(zd,wname);
   if (! iiw) {
      Plog(0,"zdialog_set_limits, %s not found \n",wname);
      return 0;
   }

   widget = zd->widget[iiw].widget;
   type = zd->widget[iiw].type;

   if (*type == 's')
      gtk_spin_button_set_range(GTK_SPIN_BUTTON(widget),min,max);

   if (*type == 'h' || *type == 'v')
      gtk_range_set_range(GTK_RANGE(widget),min,max);

   if (*type == 'z') {                                                           //  zspin
      zd->widget[iiw].lval = min;
      zd->widget[iiw].hval = max;
   }

   return 1;
}


//  get lower and upper limits for numeric data entry widget
//  returns 1 if OK, 0 if not a widget with limits

int zdialog_get_limits(zdialog *zd, ch *wname, double &min, double &max)
{
   int      iiw;

   min = max = 0;

   iiw = zdialog_find_widget(zd,wname);
   if (! iiw) return 0;
   if (! strstr("spin zspin hscale hscale2 vscale",zd->widget[iiw].type))
      return 0;
   min = zd->widget[iiw].lolim;
   max = zd->widget[iiw].hilim;
   return 1;
}


//  Expand a widget scale in the region around the neutral value.
//  Control small adjustments near the neutral value more precisely.
//  lval and hval: the range of values to be rescaled.
//  nval: the neutral value where the scale will be expanded the most.
//        lval <= nval <= hval

int zdialog_rescale(zdialog *zd, ch *wname, float lval, float nval, float hval)
{
   int      iiw;

   iiw = zdialog_find_widget(zd,wname);
   if (! iiw) return 0;

   if (lval > nval || nval > hval) {
      Plog(0,"zdialog_rescale, bad data: %s \n",wname);
      return 0;
   }

   zd->widget[iiw].rescale = 1;
   zd->widget[iiw].lval = lval;
   zd->widget[iiw].nval = nval;
   zd->widget[iiw].hval = hval;

   return 1;
}


//  run the dialog and send events to the event function
//
//  evfunc: int func(zdialog *zd, ch *event)
//  If present, eventFunc is called when a dialog widget is changed or the dialog
//  is completed. If a widget was changed, event is the widget name.
//  Get the new widget data with zdialog_fetch().
//  If a completion button was pressed, event is "zstat" and zd->zstat will be
//  the button number 1-N.
//  If the dialog was destroyed, event is "zstat" and zd->zstat is negative.
//
//  posn: optional dialog box position:
//    "mouse" = position at mouse
//    "desktop" = center on desktop                      DEFAULT
//    "parent" = center on parent window
//    "nn/nn" = position NW corner at relative x/y position in parent window,
//              where nn/nn is a percent 0-100 of the parent window dimensions.
//    "save" = save last user-set position and use this whenever the dialog
//             is repeated, also across sessions.
//
//  KBevent: extern void KBevent(GdkEventKey *event)
//  This function must be supplied by the caller of zdialog.
//  It is called when Ctrl|Shift|Alt|F1 is pressed.

int zdialog_run(zdialog *zd, zdialog_event evfunc, ch *posn)
{
   int   zdialog_KB_press(GtkWidget *, GdkEventKey *event, zdialog *zd);
   int   zdialog_focus_in_event(GtkWidget *, GdkEvent *event, zdialog *zd);

   GtkWidget   *dialog;

   if (! zdialog_valid(zd)) return 0;
   if (zd->zrunning) {
      Plog(0,"zdialog is already running \n");
      return 0;
   }

   if (posn) zdialog_set_position(zd,posn);                                      //  put dialog at desired position
   else zdialog_set_position(zd,"desktop");                                      //  use default

   if (evfunc) zd->eventCB = (void *) evfunc;                                    //  link to dialog event callback

   Plog(1,"dialog started: %s \n",zd->title);

   dialog = zd->widget[0].widget;
   gtk_widget_show_all(dialog);                                                  //  activate dialog

   G_SIGNAL(dialog,"focus-in-event",zdialog_focus_in_event,zd);                  //  connect focus event function
   G_SIGNAL(dialog,"key-press-event",zdialog_KB_press,zd);                       //  connect key press event function
   G_SIGNAL(dialog,"delete-event",zdialog_delete_event,zd);                      //  connect delete event function

   zd->zstat = 0;                                                                //  dialog status incomplete
   zd->disabled = 0;                                                             //  enable widget events
   zd->zrunning = 1;                                                             //  dialog is running
   return 0;
}


//  zdialog event handler - called for dialog events.
//  Updates data in zdialog, calls user callback function (if present).
//  private function

int zdialog_widget_event(GtkWidget *widget, zdialog *zd)
{
   zdialog_event  *evfunc = 0;                                                   //  dialog event callback function

   GtkTextView       *textView = 0;
   GtkTextBuffer     *textBuff = 0;
   GtkTextIter       iter1, iter2;
   GdkRGBA           gdkrgba;
   int               ii, nn;
   ch                *wname, *wtype, *wdata;
   ch                *pp, sdata[20];
   double            dval;
   float             lval, nval, hval, F;

   if (! zdialog_valid2(zd)) return 1;                                           //  zdialog gone
   if (zd->disabled) return 1;                                                   //  events disabled

   zd->disabled = 1;                                                             //  disable nested events

   for (ii = 0; ii < zdmaxbutts; ii++) {                                         //  check completion buttons
      if (zd->compwidget[ii] == null) break;                                     //  EOL
      if (zd->compwidget[ii] != widget) continue;
      zd->zstat = ii+1;                                                          //  zdialog status = button no.
      strncpy0(zd->event,"zstat",40);
      strncpy0(zd->zstat_button,zd->compbutton[ii],40);                          //  button label "Cancel" etc.
      wtype = "completion button";
      Plog(1,"dialog: %s  button: %s \n",zd->title,zd->zstat_button);
      goto call_evfunc;                                                          //  call zdialog event function
   }

   for (ii = 1; zd->widget[ii].type; ii++)                                       //  find widget in zdialog
      if (zd->widget[ii].widget == widget) goto found_widget;

   for (ii = 1; zd->widget[ii].type; ii++) {                                     //  failed, test if buffer
      if (strmatchV(zd->widget[ii].type,"zedit","zentry",null)) {                //    of text view widget
         textView = GTK_TEXT_VIEW(zd->widget[ii].widget);
         textBuff = gtk_text_view_get_buffer(textView);
         if (widget == (GtkWidget *) textBuff) goto found_widget;
      }
   }

   Plog(0,"zdialog event ignored: %s \n",zd->title);                             //  not found, ignore event
   zd->disabled = 0;
   return 1;

found_widget:

   wname = zd->widget[ii].wname;
   wtype = zd->widget[ii].type;
   wdata = 0;

   Plog(2,"dialog: %s  event: %s \n",zd->title,wname);                           //  Floglevel=2 to log dialog inputs

   if (strmatch(wtype,"button"))
      wdata = (ch *) gtk_button_get_label(GTK_BUTTON(widget));                   //  button label

   if (strmatch(wtype,"zbutton")) {                                              //  checkbox as smaller button
      wdata = (ch *) gtk_button_get_label(GTK_BUTTON(widget));
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget),0);                 //  reset checkmark = off
   }

   if (strmatch(wtype,"zedit")) {                                                //  multi-line
      gtk_text_buffer_get_bounds(textBuff,&iter1,&iter2);
      wdata = gtk_text_buffer_get_text(textBuff,&iter1,&iter2,0);
   }

   if (strmatch(wtype,"entry"))
      wdata = (ch *) gtk_entry_get_text(GTK_ENTRY(widget));

   if (strmatch(wtype,"zentry")) {                                               //  single line
      gtk_text_buffer_get_bounds(textBuff,&iter1,&iter2);
      wdata = gtk_text_buffer_get_text(textBuff,&iter1,&iter2,0);
      pp = strchr(wdata,GDK_KEY_Linefeed);                                       //  prohibit return character
      if (pp) {
         *pp = 0;
         gtk_text_buffer_set_text(textBuff,wdata,-1);                            //  works, generates bogus error message
      }
   }

   if (strmatchV(wtype,"radio","check","togbutt",null))
   {
      nn = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
      if (nn == 0) wdata = "0";
      else wdata = "1";
   }

   if (strmatch(wtype,"combo"))
      wdata = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(widget));

   if (strmatch(wtype,"spin"))
   {
      dval = gtk_spin_button_get_value(GTK_SPIN_BUTTON(widget));
      snprintf(sdata,20,"%g",dval);
      wdata = sdata;
   }

   if (strmatch(wtype,"colorbutt"))                                              //  color button
   {
      gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(widget),&gdkrgba);
      snprintf(sdata,20,"%.0f|%.0f|%.0f",gdkrgba.red*255,gdkrgba.green*255,gdkrgba.blue*255);
      wdata = sdata;
   }

   if (strmatchV(wtype,"hscale","hscale2","vscale",null))
   {
      dval = gtk_range_get_value(GTK_RANGE(widget));

      if (zd->widget[ii].rescale)                                                //  slider value --> widget value
      {
         lval = zd->widget[ii].lval;
         nval = zd->widget[ii].nval;
         hval = zd->widget[ii].hval;

         if (dval > lval && dval < nval) {                                       //  lval ... nval
            F = (nval - dval) / (nval - lval);                                   //  1 ... 0
            dval = (1.0 - F * F) * (nval - lval) + lval;                         //  lval ... nval
         }

         else if (dval > nval && dval < hval) {                                  //  nval ... hval
            F = (dval - nval) / (hval - nval);                                   //  0 ... 1
            dval = F * F * (hval - nval) + nval;                                 //  nval ... hval
         }
      }

      snprintf(sdata,20,"%g",dval);
      wdata = sdata;
   }

   //  all widgets come here

   if (zd->widget[ii].data) zfree(zd->widget[ii].data);                          //  clear prior data
   zd->widget[ii].data = 0;
   if (wdata) zd->widget[ii].data = zstrdup(wdata,"zdialog");                    //  set new data
   zd->lastwidget = widget;                                                      //  remember last widget updated
   strncpy0(zd->event,wname,40);                                                 //  event = widget name

call_evfunc:                                                                     //  call zdialog event function
   
   if (zd->eventCB) {
      evfunc = (zdialog_event *) zd->eventCB;                                    //  do callback function
      evfunc(zd,zd->event);
   }

   if (zdialog_valid2(zd)) zd->disabled = 0;                                     //  'event' may cause zdialog_free()
   return 1;
}


//  special zdialog handler for GtkTextView widgets
//  track current input widget for popup_text

int textview_focus_in_event(GtkWidget *widget)
{
   curr_textview_widget = GTK_TEXT_VIEW(widget);
   return 1;
}


//  zdialog response handler for "focus-in-event" signal
//  private function

zdialog  *zdialog_focus_zd;                                                      //  current zdialog

int zdialog_focus_in_event(GtkWidget *, GdkEvent *event, zdialog *zd)
{
   if (! zdialog_valid2(zd)) return 0;
   if (zd->zstat) return 0;                                                      //  already complete
   zdialog_focus_zd = zd;
   zdialog_send_event(zd,"focus");                                               //  notify dialog event function
   return 0;                                                                     //  must be 0
}


//  zdialog response handler for "activate" signal
//  private function

int zdialog_activate_event(GtkWidget *, zdialog *zd)
{
   if (! zdialog_valid2(zd)) return 0;
   if (zd->zstat) return 0;                                                      //  already complete
   zdialog_send_event(zd,"activate");                                            //  notify dialog event function
   return 0;                                                                     //  must be 0
}


//  zdialog response handler for keyboard events
//  key symbols can be found at /usr/include/gtk-3.0/gdk/gdkkeysyms.h
//  main app must provide: extern void KBevent(GdkEventKey *event)
//  private function

int zdialog_KB_press(GtkWidget *widget, GdkEventKey *kbevent, zdialog *zd)
{
   void  zdialog_copyfunc(GtkWidget *, GtkClipboard *);
   void  zdialog_pastefunc(GtkClipboard *, ch *, void *);

   GtkWidget   *focuswidget;
   int         KB_Ctrl = 0;
   int         KBkey = kbevent->keyval;
   ch          *type;
   int         ii;

   if (kbevent->state & GDK_CONTROL_MASK) KB_Ctrl = 1;

   if (KBkey == GDK_KEY_Escape) {                                                //  escape key
      Plog(3,"zdialog escape key \n");
      Fescape = 1;
      zd->zstat = -2;
      if (zd->eventCB) zdialog_send_event(zd,"zstat");
      return 1;
   }

   if (KBkey == GDK_KEY_F1) { KBevent(kbevent); return 1; };                     //  these keys handled by main app window
   if (KBkey == GDK_KEY_F10) { KBevent(kbevent); return 1; };
   if (KBkey == GDK_KEY_F11) { KBevent(kbevent); return 1; };

   if (KB_Ctrl && KBkey == GDK_KEY_h) { KBevent(kbevent); return 1; };           //  Ctrl+h  (help, user guide)            24.10

   focuswidget = gtk_window_get_focus(GTK_WINDOW(widget));                       //  find widget in zdialog

   for (ii = 1; zd->widget[ii].type; ii++)
      if (zd->widget[ii].widget == focuswidget) break;

   type = zd->widget[ii].type;                                                   //  screening input widget types removed
   if (! type) return 0;

/***
   cch   *editwidgets = "entry zentry zedit spin zspin hscale hscale2 vscale";
   if (! strstr(editwidgets,type)) {                                             //  unless widget type edit,
      if (KBkey == GDK_KEY_Left) { KBevent(kbevent); return 1; };                //    arrow keys --> main window          24.50
      if (KBkey == GDK_KEY_Right) { KBevent(kbevent); return 1; };
   }
***/

   strncpy0(zd->event,zd->widget[ii].wname,40);                                  //  save event name
   return 0;                                                                     //  pass KB key to widget 
}


//  event function for "zspin" widget

int zdialog_zspin_event(GtkWidget *widget, GdkEvent *event, zdialog *zd)
{
   zdialog_event  *evfunc = 0;                                                   //  dialog event callback function

   GtkTextBuffer        *textBuff;
   GtkTextIter          iter1, iter2;

   int         KBkey;
   int         ii, err, Nsteps, state, incr = 0;
   double      fdata, lolim, hilim, step;                                        //  double
   ch          *wdata, sdata[20];
   int         time, elaps, Fchanged;
   static int  time0 = 0, time1 = 0;

   if (event->type < 0) return 1;                                                //  GDK bug ?

   if (! zdialog_valid2(zd)) return 0;                                           //  event after dialog destroyed
   if (zd->disabled) return 0;                                                   //  zdialog events disabled

   for (ii = 1; zd->widget[ii].type; ii++)                                       //  find "zspin" (text view) widget
      if (zd->widget[ii].widget == widget) break;
   if (! zd->widget[ii].type) return 0;                                          //  not found

   textBuff = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));                   //  get widget data
   gtk_text_buffer_get_bounds(textBuff,&iter1,&iter2);
   wdata = gtk_text_buffer_get_text(textBuff,&iter1,&iter2,0);

   lolim = zd->widget[ii].lolim;                                                 //  limits and step size
   hilim = zd->widget[ii].hilim;
   step = zd->widget[ii].step;

   if (event->type == GDK_SCROLL) {                                              //  mouse wheel event
      gtk_widget_grab_focus(widget);
      incr = - ((GdkEventScroll *) event)->delta_y;
      if (! incr) return 0;
      state = ((GdkEventScroll *) event)->state;                                 //  if shift key held, use 10x step
      if (state & GDK_SHIFT_MASK) incr *= 10;
      goto checklimits;
   }

   if (event->type == GDK_KEY_PRESS) {                                           //  KB button press
      KBkey = ((GdkEventKey *) event)->keyval;
      if (KBkey == GDK_KEY_Return) goto checklimits;                             //  return = entry finished
      if (KBkey == GDK_KEY_Up) incr = 1;
      if (KBkey == GDK_KEY_Down) incr = -1;
      if (! incr) return 0;                                                      //  must return 0

      state = ((GdkEventKey *) event)->state;                                    //  if shift key held, use 10x step
      if (state & GDK_SHIFT_MASK) incr *= 10;

      time = ((GdkEventKey *) event)->time;                                      //  track time key is held down
      if (time - time1 > 300) time0 = time;
      time1 = time;
      elaps = time - time0;

      if (elaps > 5000) step = 10 * step;                                        //  acceleration table for
      else if (elaps > 4500) step = 9 * step;                                    //    hold time 1-5+ seconds
      else if (elaps > 4000) step = 8 * step;                                    //  use integer values only
      else if (elaps > 3500) step = 7 * step;
      else if (elaps > 3000) step = 6 * step;
      else if (elaps > 2500) step = 5 * step;
      else if (elaps > 2000) step = 4 * step;
      else if (elaps > 1500) step = 3 * step;
      else if (elaps > 1000) step = 2 * step;
      goto checklimits;
   }

   if (event->type == GDK_FOCUS_CHANGE) goto checklimits;                        //  focus change = entry finished
   if (event->type == GDK_LEAVE_NOTIFY) goto checklimits;                        //  pointer out - entry finished
   return 0;

checklimits:

   convSD(wdata,fdata);                                                          //  ignore bad char. inputs
   fdata += incr * step;

   Nsteps = (fdata - lolim) / step + 0.5;                                        //  set nearest exact step
   fdata = lolim + Nsteps * step;

   err = 0;

   if (fdata < lolim) {                                                          //  force within range
      err = 1;
      fdata = lolim;
   }

   if (fdata > hilim) {
      err = 2;
      fdata = hilim;
   }

   if (err) gtk_widget_grab_focus(widget);                                       //  if error, restore focus

   convDS(fdata,7,sdata);                                                        //  round to 7 digits
   gtk_text_buffer_set_text(textBuff,sdata,-1);                                  //  insert recognized value

   Fchanged = 0;
   if (zd->widget[ii].data) {
      if (! strmatch(zd->widget[ii].data,sdata)) Fchanged = 1;                   //  detect if widget data changed
      zfree(zd->widget[ii].data);                                                //  clear prior widget data
   }
   zd->widget[ii].data = zstrdup(sdata,"zdialog");                               //  set new data

   zd->lastwidget = widget;                                                      //  remember last widget updated
   strncpy0(zd->event,zd->widget[ii].wname,40);                                  //  event = widget name

   if (Fchanged)
      Plog(2,"dialog: %s  event: %s \n",zd->title,zd->widget[ii].wname);         //  Floglevel=2 to log dialog inputs

   if (zd->eventCB && Fchanged) {                                                //  if widget data changed
      zd->disabled = 1;
      evfunc = (zdialog_event *) zd->eventCB;                                    //  do event callback function
      evfunc(zd,zd->event);
      if (zdialog_valid2(zd)) zd->disabled = 0;                                  //  'event' may cause zdialog_free()
   }

   if (event->type == GDK_FOCUS_CHANGE) return 0;                                //  no propagate
   return 1;                                                                     //  propagate
}


//  process Ctrl+C (copy text from widget to clipboard)
//  private function

void zdialog_copyfunc(GtkWidget *widget, GtkClipboard *clipboard)
{
   GtkTextView    *textView = 0;
   GtkTextBuffer  *textBuff = 0;
   zdialog        *zd;
   int            ii, cc = 0;
   ch             *wname;
   ch             text[1000];

   widget = gtk_window_get_focus(GTK_WINDOW(widget));
   if (! widget) return;

   zd = zdialog_focus_zd;
   if (! zdialog_valid2(zd)) return;

   for (ii = 1; zd->widget[ii].type; ii++)                                       //  find widget in zdialog
      if (zd->widget[ii].widget == widget) goto found_widget;
   for (ii = 1; zd->widget[ii].type; ii++) {                                     //  failed, test if buffer
      if (strmatchV(zd->widget[ii].type,"zedit","zentry",null)) {                //    of text view widget
         textView = GTK_TEXT_VIEW(zd->widget[ii].widget);
         textBuff = gtk_text_view_get_buffer(textView);
         if (widget == (GtkWidget *) textBuff) goto found_widget;
      }
   }
   return;                                                                       //  not found

found_widget:
   wname = zd->widget[ii].wname;
   zdialog_fetch(zd,wname,text,999);                                             //  current text in widget
   cc = strlen(text);
   gtk_clipboard_set_text(clipboard,text,cc);
   return;
}


//  process Ctrl+V (paste text from clipboard to widget with KB focus)
//  private function

void zdialog_pastefunc(GtkClipboard *clipboard, ch *cliptext, void *arg)
{
   GtkWindow      *window;
   GtkWidget      *widget;
   GtkTextView    *textView = 0;
   GtkTextBuffer  *textBuff = 0;
   zdialog        *zd;
   int            ii, cc = 0;
   ch             *wname;
   ch             text[1000];

   window = (GtkWindow *) arg;
   widget = gtk_window_get_focus(window);
   if (! widget) return;                                                         //  widget for pasted text
   if (! cliptext || ! *cliptext) return;                                        //  clipboard text pasted

   zd = zdialog_focus_zd;
   if (! zdialog_valid2(zd)) return;

   if (zd->zstat) return;

   for (ii = 1; zd->widget[ii].type; ii++)                                       //  find widget in zdialog
      if (zd->widget[ii].widget == widget) goto found_widget;
   for (ii = 1; zd->widget[ii].type; ii++) {                                     //  failed, test if buffer
      if (strmatchV(zd->widget[ii].type,"zedit","zentry",null)) {                //    of text view widget
         textView = GTK_TEXT_VIEW(zd->widget[ii].widget);
         textBuff = gtk_text_view_get_buffer(textView);
         if (widget == (GtkWidget *) textBuff) goto found_widget;
      }
   }
   return;                                                                       //  not found

found_widget:
   wname = zd->widget[ii].wname;
   zdialog_fetch(zd,wname,text,999);                                             //  current text in widget
   cc = strlen(text);
   if (cc > 995) return;
   strncpy(text+cc,cliptext,999-cc);                                             //  add clipboard text
   text[999] = 0;
   zdialog_stuff(zd,wname,text);
   return;
}


//  private function called when zdialog is completed.
//  called when dialog is canceled via [x] button or destroyed by GTK (zstat < 0).

int zdialog_delete_event(GtkWidget *, GdkEvent *, zdialog *zd)
{
   zdialog_event  *evfunc = 0;                                                   //  dialog event callback function
   
   if (! zd) return 0;                                                           //  24.20

   zd->widget[0].widget = 0;                                                     //  widget no longer valid

   if (! zdialog_valid2(zd)) return 1;                                           //  already destroyed
   if (zd->zstat) return 1;                                                      //  already complete
   if (zd->disabled) return 1;                                                   //  in process

   zd->zstat = -1;                                                               //  set zdialog cancel status

   Plog(0,"dialog: %s killed\n",zd->title);

   if (zd->eventCB) {
      evfunc = (zdialog_event *) zd->eventCB;                                    //  do callback function
      zd->disabled = 1;
      evfunc(zd,"zstat");
      if (zdialog_valid2(zd)) zd->disabled = 0;                                  //  'event' may cause zdialog_free()
   }

   zdialog_free(zd);
   return 0;
}


//  Send an event name to an active zdialog.
//  The response function eventFunc() will be called with this event.
//  zdialog completion buttons KB shortcuts removed                              //  24.20

int zdialog_send_event(zdialog *zd, ch *event)
{
   zdialog_event * evfunc = 0;                                                   //  dialog event callback function

   if (! zdialog_valid2(zd)) return 0;                                           //  zdialog canceled
   if (zd->disabled) return 0;                                                   //  zdialog busy

   evfunc = (zdialog_event *) zd->eventCB;
   if (! evfunc) return 0;
   zd->disabled = 1;
   Plog(3,"zdialog send event: %s \n",event);
   evfunc(zd,event);                                                             //  call dialog event function
   if (zdialog_valid2(zd)) zd->disabled = 0;                                     //  'event' may cause zdialog_free()
   return 1;
}


//  Complete an active dialog and assign a status.
//  Equivalent to the user pressing a dialog completion button.
//  The dialog completion function is called if defined,
//  and zdialog_wait() is unblocked.
//  returns:  0 = no active dialog or completion function, 1 = OK

int zdialog_send_response(zdialog *zd, int zstat)
{
   zdialog_event  *evfunc = 0;                                                   //  dialog event callback function

   if (! zdialog_valid2(zd)) return 0;
   if (zd->disabled) return 0;
   zd->zstat = zstat;                                                            //  set status
   evfunc = (zdialog_event *) zd->eventCB;
   if (! evfunc) return 0;
   zd->disabled = 1;
   evfunc(zd,"zstat");
   if (zdialog_valid2(zd)) zd->disabled = 0;                                     //  'event' may cause zdialog_free()
   return 1;
}


//  show or hide a zdialog window
//  returns 1 if successful, 0 if zd does not exist.

int zdialog_show(zdialog *zd, int show)
{
   static GtkWidget  *widget, *pwidget = 0;
   static int        posx, posy;

   if (! zdialog_valid(zd)) return 0;

   widget = zdialog_gtkwidget(zd,"dialog");

   if (show) {                                                                   //  show window
      if (widget == pwidget) {                                                   //  restore prior position
         gtk_window_move(GTK_WINDOW(widget),posx,posy);
         pwidget = 0;
      }
      gtk_widget_show_all(widget);
      gtk_window_present(GTK_WINDOW(widget));                                    //  set focus on restored window
   }
   else {                                                                        //  hide window
      pwidget = widget;
      gtk_window_get_position(GTK_WINDOW(widget),&posx,&posy);                   //  save position
      gtk_widget_hide(widget);
   }
   return 1;
}


//  Destroy the zdialog - must be done by zdialog_run() caller
//  (else dialog continues active even after completion button).
//  Data in widgets remains valid until zdialog_free() is called.

int zdialog_destroy(zdialog *zd)
{
   if (! zdialog_valid2(zd)) return 0;                                           //  destroyed, not freed yet

   if (zd->saveposn) zdialog_save_position(zd);                                  //  save position for next use

   if (zd->widget[0].widget) {                                                   //  multiple destroys OK
      gtk_widget_destroy(zd->widget[0].widget);                                  //  destroy GTK dialog
      zd->widget[0].widget = 0;
   }

   if (! zd->zstat) zd->zstat = -1;                                              //  status = destroyed
   zd->zrunning = 0;                                                             //  not running
   zd->disabled = 1;                                                             //  ignore events after destroy
   return 1;
}


//  free zdialog memory (will destroy first, if not already)
//  zd is set to null

int zdialog_free(zdialog *&zd)                                                   //  reference
{
   int      ii;
   
   if (! zd) return 0;                                                           //  24.20

   if (! zdialog_valid2(zd)) return 0;                                           //  validate zd pointer

   zdialog_save_inputs(zd);                                                      //  save user inputs for next use

   zdialog_destroy(zd);                                                          //  destroy GTK dialog if there

   zd->sentinel1 = zd->sentinel2 = 0;                                            //  mark sentinels invalid
   zfree(zd->title);                                                             //  free title memory
   zfree(zd->widget[0].data);

   for (ii = 1; zd->widget[ii].type; ii++)                                       //  loop through widgets
   {
      zfree((ch *) zd->widget[ii].type);                                         //  free strings
      zfree((ch *) zd->widget[ii].wname);
      if (zd->widget[ii].pname) zfree((ch *) zd->widget[ii].pname);              //  parent widget name
      if (zd->widget[ii].data) zfree(zd->widget[ii].data);                       //  free data
      if (zd->widget[ii].zlist) zlist_free(zd->widget[ii].zlist);                //  free combo box zlist
   }

   for (ii = 0; ii < zdialog_count; ii++)                                        //  remove from valid zdialog list
      if (zd == zdialog_list[ii]) break;
   if (ii < zdialog_count) {
      zdialog_count--;
      for (NOP; ii < zdialog_count; ii++)                                        //  pack down list
         zdialog_list[ii] = zdialog_list[ii+1];
   }
   else Plog(0,"zdialog_free(), not in zdialog_list \n");

   zfree(zd);                                                                    //  free zdialog memory
   zd = 0;                                                                       //  caller pointer = null
   return 1;
}


//  Wait for a dialog to complete or be destroyed. This is a zmainloop() loop.
//  The returned status is the button 1-N used to complete the dialog, or negative
//  if the dialog was destroyed with [x] or otherwise by GTK. If the status was 1-N and
//  the dialog will be kept active, set zd->zstat = 0 to restore the active state.

int zdialog_wait(zdialog *zd)
{
   zdialog_present(zd);                                                          //  initially has focus
   
   while (true)
   {
      zmainsleep(0.01);
      if (! zd) return -1;
      if (! zdialog_valid2(zd)) return -1;
      if (zd->zstat) return zd->zstat;
   }
}


//  put cursor at named widget

int zdialog_goto(zdialog *zd, ch *wname)
{
   GtkWidget   *widget;

   if (! zdialog_valid(zd)) return 0;

   widget = zdialog_gtkwidget(zd, wname);
   if (! widget) return 0;
   gtk_widget_grab_focus(widget);

   return 1;
}


//  set cursor for zdialog (e.g. a busy cursor)

void zdialog_set_cursor(zdialog *zd, GdkCursor *cursor)
{
   GtkWidget   *dialog;
   GdkWindow   *window;

   if (! zdialog_valid(zd)) return;
   dialog = zd->widget[0].widget;
   if (! dialog) return;
   window = gtk_widget_get_window(dialog);
   gdk_window_set_cursor(window,cursor);
   return;
}


//  insert data into a zdialog widget

int zdialog_stuff(zdialog *zd, ch *wname, ch *data)                              //  stuff a string
{
   if (data) zdialog_put_data(zd,wname,data);
   else zdialog_put_data(zd,wname,"");                                           //  null > ""
   return 1;
}

int zdialog_stuff(zdialog *zd, ch *wname, int idata)                             //  stuff an integer
{
   ch       string[16];
   double   min, max;

   if (zdialog_get_limits(zd,wname,min,max))
      if (idata < min || idata > max) return 0;                                  //  bad data, do nothing
   snprintf(string,16,"%d",idata);
   zdialog_put_data(zd,wname,string);
   return 1;
}

int zdialog_stuff(zdialog *zd, ch *wname, double ddata)                          //  stuff a double
{
   ch       string[32];
   double   min, max;

   if (zdialog_get_limits(zd,wname,min,max))
      if (ddata < min || ddata > max) return 0;                                  //  bad data, do nothing
   snprintf(string,32,"%.7g",ddata);                                             //  increase from 6 to 7 digits
   zdialog_put_data(zd,wname,string);                                            //  'g' uses decimal or comma
   return 1;                                                                     //      (per locale)
}

int zdialog_stuff(zdialog *zd, ch *wname, double ddata, ch *format)              //  stuff a double, formatted
{
   ch       string[32];
   double   min, max;

   if (zdialog_get_limits(zd,wname,min,max))
      if (ddata < min || ddata > max) return 0;                                  //  bad data, do nothing
   snprintf(string,32,format,ddata);                                             //  use "%.2g" etc. for
   zdialog_put_data(zd,wname,string);                                            //    locale dependent point/comma
   return 1;
}

int zdialog_labelfont(zdialog *zd, ch *labl, ch *font, ch *txt)                  //  stuff label text using specified font
{
   GtkWidget   *widget;
   ch          *format =  "<span font=\"%s\" >%s</span>";
   ch          txt2[1000];

   if (! font) font = zfuncs::appfont;                                           //  default font
   snprintf(txt2,1000,format,font,txt);
   widget = zdialog_gtkwidget(zd,labl);
   gtk_label_set_markup(GTK_LABEL(widget),txt2);
   return 1;
}


//  get data from a zdialog widget

int zdialog_fetch(zdialog *zd, ch *wname, ch *data, int maxcc)                   //  fetch string data
{
   ch  *zdata;

   zdata = zdialog_get_data(zd,wname);
   if (! zdata) {
      *data = 0;
      return 0;
   }

   return strncpy0(data,zdata,maxcc);                                            //  0 = OK, 1 = truncation
}

int zdialog_fetch(zdialog *zd, ch *wname, int &idata)                            //  fetch an integer
{
   ch  *zdata;

   zdata = zdialog_get_data(zd,wname);
   if (! zdata) {
      idata = 0;
      return 0;
   }

   idata = atoi(zdata);
   return 1;
}

int zdialog_fetch(zdialog *zd, ch *wname, double &ddata)                         //  fetch a double
{
   int         stat;
   ch          *zdata;

   zdata = zdialog_get_data(zd,wname);
   if (! zdata) {
      ddata = 0;
      return 0;
   }

   stat = convSD(zdata,ddata);                                                   //  period or comma decimal point OK
   if (stat < 4) return 1;
   return 0;
}

int zdialog_fetch(zdialog *zd, ch *wname, float &fdata)                          //  fetch a float
{
   int         stat;
   ch          *zdata;
   double      ddata;

   zdata = zdialog_get_data(zd,wname);
   if (! zdata) {
      fdata = 0;
      return 0;
   }

   stat = convSD(zdata,ddata);                                                   //  period or comma decimal point OK
   fdata = ddata;
   if (stat < 4) return 1;
   return 0;
}


//  clear combo box entries

int zdialog_combo_clear(zdialog *zd, ch *wname)
{
   int         ii;

   ii = zdialog_find_widget(zd,wname);
   if (! ii) return 0;
   gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(zd->widget[ii].widget));     //  remove all entries
   if (zd->widget[ii].zlist) zlist_clear(zd->widget[ii].zlist,0);
   return 1;
}


//  popup (open) combo box pick list

int zdialog_combo_popup(zdialog *zd, ch *wname)
{
   int      ii;

   ii = zdialog_find_widget(zd,wname);
   if (! ii) return 0;
   gtk_combo_box_popup(GTK_COMBO_BOX(zd->widget[ii].widget));
   return 1;
}


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

//  Load/save all function widget data from/to a file.
//  dirname for data files: /home/<user>/.appname/funcname
//    where zdialog data is saved for the respective function.
//  return 0 = OK, +N = error

int zdialog_load_widgets(zdialog *zd, spldat *sd, ch *funcname, FILE *fid)
{
   using namespace zfuncs;

   ch       *mess = "Load settings from file";
   int      myfid = 0;
   ch       *filename, dirname[200], buff[1000];
   ch       *wname, *wdata, wdata2[1000];
   ch       *pp, *pp1, *pp2;
   int      ii, kk, err, cc1, cc2;

   if (! fid)                                                                    //  fid from script
   {
      snprintf(dirname,200,"%s/%s",get_zhomedir(),funcname);                     //  folder for data files
      filename = zgetfile(mess,GTK_WINDOW(mainwin),"file",dirname,0);            //  open data file
      if (! filename) return 1;                                                  //  user cancel
      fid = fopen(filename,"r");
      zfree(filename);
      if (! fid) {
         zmessageACK(mainwin,"%s \n %s",filename,strerror(errno));
         return 1;
      }
      myfid = 1;
   }

   for (ii = 0; ii < zdmaxwidgets; ii++)                                         //  read widget data recs
   {
      pp = fgets_trim(buff,1000,fid,1);
      if (! pp) break;
      if (strmatch(pp,"curves")) {
         if (! sd) goto baddata;
         err = splcurve_load(sd,fid);                                            //  load curves data
         if (err) goto baddata;
         continue;
      }
      if (strmatch(pp,"end")) break;
      pp1 = pp;
      pp2 = strstr(pp1," ==");
      if (! pp2) continue;                                                       //  widget has no data
      cc1 = pp2 - pp1;
      if (cc1 > 100) continue;
      pp1[cc1] = 0;
      wname = pp1;                                                               //  widget name
      if (strstr("defcats deftags",wname)) continue;                             //  fotocx only kludge
      pp2 += 3;
      if (*pp2 == ' ') pp2++;
      wdata = pp2;                                                               //  widget data
      cc2 = strlen(wdata);
      if (cc2 < 1) wdata = "";
      if (cc2 > 1000) continue;
      repl_1str(wdata,wdata2,1000,"\\n","\n");                                   //  replace "\n" with newline chars.
      kk = zdialog_put_data(zd,wname,wdata2);
      if (! kk) goto baddata;
      Plog(2,"put dialog data: %s %s \n",wname,wdata2);                          //  24.30
   }

   if (myfid) fclose(fid);
   return 0;

baddata:
   zmessageACK(mainwin,"file data does not fit dialog");
   if (myfid) fclose(fid);
   return 1;
}


int zdialog_save_widgets(zdialog *zd, spldat *sd, ch *funcname, FILE *fid)
{
   using namespace zfuncs;

   ch       *mess = "Save settings to a file";
   int      myfid = 0;
   ch       *filename, dirname[200];
   ch       *wtype, *wname, *wdata, wdata2[1000];
   int      ii, cc;

   ch       *editwidgets = "entry zentry edit text togbutt check combo"          //  widget types to save
                           "radio spin zspin hscale hscale2 vscale colorbutt";
   ch       *editwidgetsX = "defcats deftags";                                   //  exclude list, fotocx kludge

   if (! fid)                                                                    //  fid from script
   {
      snprintf(dirname,200,"%s/%s",get_zhomedir(),funcname);                     //  folder for data files
      filename = zgetfile(mess,GTK_WINDOW(mainwin),"save",dirname,0);            //  open data file
      if (! filename) return 1;                                                  //  user cancel
      fid = fopen(filename,"w");
      zfree(filename);
      if (! fid) {
         zmessageACK(mainwin,"%s \n %s",filename,strerror(errno));
         return 1;
      }
      myfid = 1;
   }

   for (ii = 0; ii < zdmaxwidgets; ii++)
   {
      wtype = (ch *) zd->widget[ii].type;
      if (! wtype) break;
      if (! strstr(editwidgets,wtype)) continue;
      wname = (ch *) zd->widget[ii].wname;                                       //  write widget data recs:
      if (strstr(editwidgetsX,wname)) continue;
      wdata = zd->widget[ii].data;                                               //  widgetname == widgetdata
      if (! wdata) continue;
      cc = strlen(wdata);
      if (cc > 900) continue;
      repl_1str(wdata,wdata2,1000,"\n","\\n");                                   //  replace newline with "\n"
      fprintf(fid,"%s == %s \n",wname,wdata);
   }

   if (sd) {
      fprintf(fid,"curves\n");
      splcurve_save(sd,fid);
   }

   fprintf(fid,"end\n");

   if (myfid) fclose(fid);
   return 0;
}


//  functions to support [prev] buttons in function dialogs
//  load or save last-used widgets

int zdialog_load_prev_widgets(zdialog *zd, spldat *sd, ch *funcname)
{
   using namespace zfuncs;

   ch       filename[200];
   FILE     *fid;
   int      err;

   snprintf(filename,200,"%s/%s/last-used",get_zhomedir(),funcname);
   fid = fopen(filename,"r");
   if (! fid) {
      zmessageACK(mainwin,"%s \n %s",filename,strerror(errno));
      return 1;
   }

   err = zdialog_load_widgets(zd,sd,funcname,fid);
   fclose(fid);
   return err;
}


int zdialog_save_last_widgets(zdialog *zd, spldat *sd, ch *funcname)
{
   using namespace zfuncs;

   ch       filename[200], dirname[200];
   FILE     *fid;
   int      err;

   snprintf(filename,200,"%s/%s/last-used",get_zhomedir(),funcname);
   fid = fopen(filename,"w");
   if (! fid) {
      snprintf(dirname,200,"%s/%s",get_zhomedir(),funcname);                     //  create missing folder
      err = mkdir(dirname,0750);
      if (err) {
         Plog(0,"%s \n %s \n",dirname,strerror(errno));
         return 1;
      }
      fid = fopen(filename,"w");                                                 //  open again
   }

   if (! fid) {
      Plog(0,"%s \n %s \n",filename,strerror(errno));
      return 1;
   }

   err = zdialog_save_widgets(zd,sd,funcname,fid);
   fclose(fid);
   return err;
}


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

//  functions to save and recall zdialog window positions

namespace zdposn_names
{
   struct zdposn_t {
      ch       wintitle[64];                                                     //  window title (ID)
      float    xpos, ypos;                                                       //  window posn WRT parent or desktop, 0-100
      int      xsize, ysize;                                                     //  window size, pixels
   }  zdposn[200];                                                               //  space to remember 200 windows

   int      Nzdposn;                                                             //  no. in use
   int      Nzdpmax = 200;                                                       //  table size
}


//  Load zdialog positions table from its file (application startup)
//  or save zdialog positions table to its file (application exit).
//  Action is "load" or "save". Number of table entries is returned.

int zdialog_geometry(ch *action)
{
   using namespace zdposn_names;

   ch       posfile[200], buff[100], wintitle[64], *pp;
   float    xpos, ypos;
   int      xsize, ysize;
   int      ii, nn, cc;
   FILE     *fid;

   snprintf(posfile,199,"%s/zdialog_geometry",zhomedir);                         //  /home/<user>/.appname/zdialog_geometry

   if (strmatch(action,"load"))                                                  //  load dialog positions table from file
   {
      fid = fopen(posfile,"r");
      if (! fid) {
         Nzdposn = 0;
         return 0;
      }

      for (ii = 0; ii < Nzdpmax; )
      {
         pp = fgets(buff,100,fid);
         if (! pp) break;
         pp = strstr(buff,"||");
         if (! pp) continue;
         cc = pp - buff;
         strncpy0(wintitle,buff,cc);
         strTrim(wintitle);
         if (strlen(wintitle) < 3) continue;
         nn = sscanf(pp+2," %f %f %d %d ",&xpos,&ypos,&xsize,&ysize);
         if (nn != 4) continue;

         strcpy(zdposn[ii].wintitle,wintitle);
         zdposn[ii].xpos = xpos;
         zdposn[ii].ypos = ypos;
         zdposn[ii].xsize = xsize;
         zdposn[ii].ysize = ysize;
         ii++;
      }

      fclose(fid);
      Nzdposn = ii;
      return Nzdposn;
   }

   if (strmatch(action,"save"))                                                  //  save dialog positions table to file
   {
      fid = fopen(posfile,"w");
      if (! fid) {
         Plog(0,"cannot write zdialog_geometry file \n");
         return 0;
      }

      for (ii = 0; ii < Nzdposn; ii++) {
         fprintf(fid,"%s || %0.1f %0.1f %d %d \n",                               //  dialog-title || xpos ypos xsize ysize
                           zdposn[ii].wintitle,
                           zdposn[ii].xpos, zdposn[ii].ypos,
                           zdposn[ii].xsize, zdposn[ii].ysize);
      }

      fclose(fid);
      return Nzdposn;
   }

   Plog(0,"zdialog_geometry bad action: %s \n",action);
   return 0;
}


//  Set the initial or new zdialog window position from "posn".
//  Called by zdialog_run().  Private function.
//     null:      window manager decides
//    "mouse"     put dialog at mouse position
//    "desktop"   center dialog in desktop window
//    "parent"    center dialog in parent window
//    "save"      use the same position last set by the user
//    "nn/nn"     put NW corner of dialog in parent window at % size
//                (e.g. "50/50" puts NW corner at center of parent)

void zdialog_set_position(zdialog *zd, ch *posn)
{
   using namespace zdposn_names;

   int         ii, ppx, ppy, zdpx, zdpy, pww, phh;
   float       xpos, ypos;
   int         xsize, ysize;
   ch          wintitle[64], *pp;
   GtkWidget   *parent, *dialog;

   if (! zdialog_valid(zd)) return;

   parent = zd->parent;
   dialog = zd->widget[0].widget;

   if (strmatch(posn,"mouse")) {
      window_to_mouse(zd->dialog);
      return;
   }

   if (strmatch(posn,"desktop")) {
      gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_CENTER);
      return;
   }

   if (strmatch(posn,"parent")) {
      gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_CENTER_ON_PARENT);
      return;
   }

   if (! parent) parent = mainwin;

   if (! parent) {                                                               //  no parent window
      ppx = ppy = 0;                                                             //  use desktop
      pww = monitor_ww;
      phh = monitor_hh;
   }
   else {
      gtk_window_get_position(GTK_WINDOW(parent),&ppx,&ppy);                     //  parent window NW corner
      gtk_window_get_size(GTK_WINDOW(parent),&pww,&phh);                         //  parent window size
   }

   if (strmatch(posn,"save"))                                                    //  use last saved window position
   {
      zd->saveposn = 1;                                                          //  set flag for zdialog_free()

      pp = (ch *) gtk_window_get_title(GTK_WINDOW(dialog));                      //  get window title, used as ID
      if (! pp || strlen(pp) < 2) goto center_parent;

      strncpy0(wintitle,pp,64);                                                  //  window title, < 64 chars.

      for (ii = 0; ii < Nzdposn; ii++)                                           //  search table for title
         if (strmatch(wintitle,zdposn[ii].wintitle)) break;
      if (ii == Nzdposn) goto center_parent;                                     //  not found - zdialog_destroy() will add

      zdpx = ppx + 0.01 * zdposn[ii].xpos * pww;                                 //  set position for dialog window
      zdpy = ppy + 0.01 * zdposn[ii].ypos * phh;
      xsize = zdposn[ii].xsize;                                                  //  set size
      ysize = zdposn[ii].ysize;
      gtk_window_move(GTK_WINDOW(dialog),zdpx,zdpy);
      gtk_window_resize(GTK_WINDOW(dialog),xsize,ysize);
      return;
   }

   else     //  "nn/nn"                                                          //  position from caller
   {
      ii = sscanf(posn,"%f/%f",&xpos,&ypos);                                     //  parse "nn/nn"
      if (ii != 2) goto center_parent;

      zdpx = ppx + 0.01 * xpos * pww;                                            //  position for dialog window
      zdpy = ppy + 0.01 * ypos * phh;
      gtk_window_move(GTK_WINDOW(dialog),zdpx,zdpy);
      return;
   }

center_parent:                                                                   //  center on parent window
   gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_CENTER_ON_PARENT);
   return;
}


//  If the dialog window position is "save" then save
//  its position WRT parent or desktop for next use.
//  called by zdialog_destroy().  Private function.

void zdialog_save_position(zdialog *zd)
{
   using namespace zdposn_names;

   int         ii, ppx, ppy, pww, phh, zdpx, zdpy;
   float       xpos, ypos;
   int         xsize, ysize;
   ch          wintitle[64], *pp;
   GtkWidget   *parent, *dialog;

   if (! zdialog_valid(zd)) return;

   dialog = zd->widget[0].widget;
   if (! dialog) return;
   if (! gtk_widget_get_window(dialog)) return;

   gtk_window_get_position(GTK_WINDOW(dialog),&zdpx,&zdpy);                      //  dialog window NW corner
   if (! zdpx && ! zdpy) return;                                                 //  (0,0) ignore

   gtk_window_get_size(GTK_WINDOW(dialog),&xsize,&ysize);                        //  window size

   parent = zd->parent;                                                          //  parent window

   if (! parent) parent = mainwin;

   if (! parent) {                                                               //  no parent window
      ppx = ppy = 0;                                                             //  use desktop
      pww = monitor_ww;
      phh = monitor_hh;
   }
   else {
      gtk_window_get_position(GTK_WINDOW(parent),&ppx,&ppy);                     //  parent window NW corner
      gtk_window_get_size(GTK_WINDOW(parent),&pww,&phh);                         //  parent window size
   }

   xpos = 100.0 * (zdpx - ppx) / pww;                                            //  dialog window relative position
   ypos = 100.0 * (zdpy - ppy) / phh;                                            //  (as percent of parent size)

   pp = (ch *) gtk_window_get_title(GTK_WINDOW(dialog));
   if (! pp) return;
   if (strlen(pp) < 2) return;
   strncpy0(wintitle,pp,64);                                                     //  window title, < 64 chars.

   for (ii = 0; ii < Nzdposn; ii++)                                              //  search table for window
      if (strmatch(wintitle,zdposn[ii].wintitle)) break;
   if (ii == Nzdposn) {                                                          //  not found
      if (ii == Nzdpmax) return;                                                 //  table full
      Nzdposn++;                                                                 //  new entry
   }

   strcpy(zdposn[ii].wintitle,wintitle);                                         //  add window to table
   zdposn[ii].xpos = xpos;                                                       //  save window position
   zdposn[ii].ypos = ypos;
   zdposn[ii].xsize = xsize;                                                     //  and window size
   zdposn[ii].ysize = ysize;
   return;
}


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

//  Functions to save and restore zdialog user inputs
//    within an app session or across app sessions.

namespace zdinputs_names
{
   #define  Nwmax zdmaxwidgets                                                   //  max. widgets in a dialog
   #define  Nzdmax 200                                                           //  max. zdialogs
   #define  ccmax1 100                                                           //  max. widget name length
   #define  ccmax2 400                                                           //  max. widget data length

   struct zdinputs_t {
      ch       *zdtitle = 0;                                                     //  zdialog title
      int      Nw;                                                               //  no. of widgets
      ch       **wname;                                                          //  list of widget names
      ch       **wdata;                                                          //  list of widget data
   }  zdinputs[Nzdmax];                                                          //  space for Nzdmax dialogs

   int      Nzd = 0;                                                             //  no. zdialogs in use
}


//  Load zdialog input fields from its file (app startup)
//  or save zdialog input fields to its file (app shutdown).
//  Action is "load" or "save".
//  Number of zdialogs is returned.

int zdialog_inputs(ch *action)
{
   using namespace zdinputs_names;

   ch       zdinputsfile[200], buff[ccmax2];
   ch       zdtitle[ccmax1], wname[Nwmax][ccmax1], wdata[Nwmax][ccmax2];
   ch       *pp, *pp1, *pp2, wdata2[ccmax2+50];
   FILE     *fid;
   int      Nw, ii, jj, cc, cc1, cc2;

   snprintf(zdinputsfile,200,"%s/zdialog_inputs",zhomedir);                      //  /home/<user>/.appname/zdialog_inputs

   if (strmatch(action,"load"))                                                  //  load dialog input fields from its file
   {
      Nzd = 0;

      fid = fopen(zdinputsfile,"r");                                             //  no file
      if (! fid) return 0;

      while (true)
      {
         pp = fgets_trim(buff,ccmax2,fid,1);                                     //  read next zdialog title record
         if (! pp) break;
         if (! strmatchN(pp,"zdialog == ",11)) continue;

         strncpy0(zdtitle,pp+11,ccmax1);                                         //  save new zdialog title

         pp = fgets_trim(buff,ccmax2,fid,1);                                     //  read widget count
         if (! pp) break;
         Nw = atoi(pp);
         if (Nw < 1 || Nw > Nwmax) {
            Plog(0,"zdialog_inputs() bad data: %s \n",zdtitle);
            continue;
         }

         for (ii = 0; ii < Nw; ii++)                                             //  read widget data recs
         {
            pp = fgets_trim(buff,ccmax2,fid,1);
            if (! pp) break;
            pp1 = pp;
            pp2 = strstr(pp1," ==");
            if (! pp2) break;                                                    //  widget has no data
            cc1 = pp2 - pp1;
            pp1[cc1] = 0;
            pp2 += 3;
            if (*pp2 == ' ') pp2++;
            cc2 = strlen(pp2);
            if (cc1 < 1 || cc1 >= ccmax1) break;
            if (cc2 < 1) pp2 = "";
            if (cc2 >= ccmax2) break;                                            //  do not copy large inputs
            strcpy(wname[ii],pp1);                                               //  save widget name and data
            strcpy(wdata2,pp2);
            repl_1str(wdata2,wdata[ii],ccmax2,"\\n","\n");                       //  replace "\n" with newline chars.
         }

         if (ii < Nw) {
            Plog(0,"zdialog_inputs() bad data: %s \n",zdtitle);
            continue;
         }

         if (Nzd == Nzdmax) {
            Plog(0,"zdialog_inputs() too many dialogs \n");
            break;
         }

         zdinputs[Nzd].zdtitle = zstrdup(zdtitle,"zdialog_inputs");              //  save acculumated zdialog data
         zdinputs[Nzd].Nw = Nw;
         cc = Nw * sizeof(ch *);
         zdinputs[Nzd].wname = (ch **) zmalloc(cc,"zdialog_inputs");
         zdinputs[Nzd].wdata = (ch **) zmalloc(cc,"zdialog_inputs");
         for (ii = 0; ii < Nw; ii++) {
            zdinputs[Nzd].wname[ii] = zstrdup(wname[ii],"zdialog_inputs");
            zdinputs[Nzd].wdata[ii] = zstrdup(wdata[ii],"zdialog_inputs");
         }

         Nzd++;
      }

      fclose(fid);
      return Nzd;
   }

   if (strmatch(action,"save"))                                                  //  save dialog input fields to its file
   {
      fid = fopen(zdinputsfile,"w");
      if (! fid) {
         Plog(0,"zdialog_inputs() cannot write file \n");
         return 0;
      }

      for (ii = 0; ii < Nzd; ii++)
      {
         fprintf(fid,"zdialog == %s \n",zdinputs[ii].zdtitle);                   //  zdialog == zdialog title
         Nw = zdinputs[ii].Nw;
         fprintf(fid,"%d \n",Nw);                                                //  widget count
         for (jj = 0; jj < Nw; jj++) {
            pp1 = zdinputs[ii].wname[jj];                                        //  widget name == widget data
            pp2 = zdinputs[ii].wdata[jj];
            repl_1str(pp2,wdata2,ccmax2+50,"\n","\\n");                          //  replace newline chars. with "\n"
            fprintf(fid,"%s == %s \n",pp1,wdata2);
         }
         fprintf(fid,"\n");
      }

      fclose(fid);
      return Nzd;
   }

   Plog(0,"zdialog_inputs bad action: %s \n",action);
   return 0;
}


//  Save dialog user input fields when a dialog is finished.
//  Called automatically by zdialog_free(). Private function.

int zdialog_save_inputs(zdialog *zd)
{
   using namespace zdinputs_names;

   ch       zdtitle[ccmax1], wname[ccmax1], wdata[ccmax2];
   ch       *wnamex, *type;
   int      ii, jj, Nw, cc;

   ch       *skipwidgets = "dialog hbox vbox hsep vsep frame scrwin"             //  non-input widgets to omit
                           "label text link button zbutton";
   ch       *skipexceptions = "searchtags";                                      //  fotocx kludge

   if (! zdialog_valid(zd)) return 0;
   if (! zd->saveinputs) return 0;                                               //  zdialog does not use this service

   strncpy0(zdtitle,zd->widget[0].data,ccmax1);                                  //  zdialog title is widget[0].data

   for (ii = 0; ii < Nzd; ii++)                                                  //  find zdialog in zdinputs table
      if (strmatch(zdtitle,zdinputs[ii].zdtitle)) break;

   if (ii < Nzd) {                                                               //  found
      zfree(zdinputs[ii].zdtitle);                                               //  delete obsolete zdinputs data
      for (jj = 0; jj < zdinputs[ii].Nw; jj++) {
         zfree(zdinputs[ii].wname[jj]);
         zfree(zdinputs[ii].wdata[jj]);
      }
      zfree(zdinputs[ii].wname);
      zfree(zdinputs[ii].wdata);
      Nzd--;                                                                     //  decr. zdialog count
      for (NOP; ii < Nzd; ii++)                                                  //  pack down the rest
         zdinputs[ii] = zdinputs[ii+1];
   }

   if (Nzd == Nzdmax) {
      Plog(0,"zdialog_save_inputs, too many zdialogs \n");
      return 0;
   }

   ii = Nzd;                                                                     //  next zdinputs table entry

   for (Nw = 0, jj = 1; zd->widget[jj].type; jj++) {                             //  count zdialog widgets
      wnamex = (ch *) zd->widget[jj].wname;
      type = (ch *) zd->widget[jj].type;
      if (strstr(skipwidgets,type))                                              //  skip non-input widgets
         if (! strstr(skipexceptions,wnamex)) continue;
      Nw++;
   }

   if (! Nw) return 0;                                                           //  no input widgets
   if (Nw > Nwmax) {
      Plog(0,"zdialog_inputs() bad data: %s \n",zdtitle);
      return 0;
   }

   zdinputs[ii].zdtitle = zstrdup(zdtitle,"zdialog_save");                       //  set zdialog title

   cc = Nw * sizeof(ch *);                                                       //  allocate pointers for widgets
   zdinputs[ii].wname = (ch **) zmalloc(cc,"zdialog_save");
   zdinputs[ii].wdata = (ch **) zmalloc(cc,"zdialog_save");

   for (Nw = 0, jj = 1; zd->widget[jj].type; jj++) {                             //  add widget names and data
      wnamex = (ch *) zd->widget[jj].wname;
      type = (ch *) zd->widget[jj].type;
      if (strstr(skipwidgets,type))                                              //  skip non-input widgets
         if (! strstr(skipexceptions,wnamex)) continue;
      strncpy0(wname,zd->widget[jj].wname,ccmax1);
      if (zd->widget[jj].data)
         strncpy0(wdata,zd->widget[jj].data,ccmax2);
      else strcpy(wdata,"");
      zdinputs[ii].wname[Nw] = zstrdup(wname,"zdialog_save");
      zdinputs[ii].wdata[Nw] = zstrdup(wdata,"zdialog_save");
      Nw++;
   }

   zdinputs[ii].Nw = Nw;                                                         //  set widget count
   Nzd++;                                                                        //  add zdialog to end of zdinputs

   return 1;
}


//  Restore user input fields from prior use of the same dialog.
//  Call this if wanted after zdialog is built and before it is run.
//  Override old user inputs with zdialog_stuff() where needed.

int zdialog_load_inputs(zdialog *zd)
{
   using namespace zdinputs_names;

   ch       *zdtitle, *wname, *wdata;
   int      ii, jj;

   zd->saveinputs = 1;                                                           //  flag, save data at zdialog_free()

   zdtitle = (ch *) zd->widget[0].data;                                          //  zdialog title

   for (ii = 0; ii < Nzd; ii++)                                                  //  find zdialog in zdinputs
      if (strmatch(zdtitle,zdinputs[ii].zdtitle)) break;
   if (ii == Nzd) return 0;                                                      //  not found

   for (jj = 0; jj < zdinputs[ii].Nw; jj++) {                                    //  stuff all saved widget data
      wname = zdinputs[ii].wname[jj];
      wdata = zdinputs[ii].wdata[jj];
      zdialog_put_data(zd,wname,wdata);
   }

   return 1;
}


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

//  get text input from a popup dialog - multiple lines can be entered
//  returned text is subject for zfree()
//  null is returned if user presses [cancel] button.

ch * zdialog_text(GtkWidget *parent, ch *title, ch *inittext)
{
   zdialog     *zd;
   int         zstat;
   ch          *text;

   if (! main_thread()) zappcrash("zdialog_text() called from thread");

   zd = zdialog_new(title,parent,"OK","Cancel",null);
   zdialog_add_widget(zd,"frame","fred","dialog");
   zdialog_add_widget(zd,"zedit","text","fred");
   if (inittext) zdialog_stuff(zd,"text",inittext);

   zdialog_resize(zd,300,0);
   zdialog_set_modal(zd);
   zdialog_run(zd,0,"mouse");
   zstat = zdialog_wait(zd);
   if (zstat == 1)
      text = (ch *) zdialog_get_data(zd,"text");
   else text = 0;
   if (text) text = zstrdup(text,"zdialog_text");
   zdialog_free(zd);
   return text;
}


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

//  get text input from a popup dialog - one line only
//  returned text is subject for zfree()
//  null is returned if user presses [cancel] button.

ch * zdialog_text1(GtkWidget *parent, ch *title, ch *inittext)
{
   zdialog     *zd;
   int         zstat;
   ch          *text;

   if (! main_thread()) zappcrash("zdialog_text1() called from thread");

   zd = zdialog_new(title,parent,"OK","Cancel",null);
   zdialog_add_widget(zd,"zentry","text","dialog",0);
   if (inittext) zdialog_stuff(zd,"text",inittext);

   zdialog_resize(zd,300,0);
   zdialog_set_modal(zd);
   zdialog_run(zd,0,"mouse");
   zstat = zdialog_wait(zd);
   if (zstat == 1)
      text = (ch *) zdialog_get_data(zd,"text");
   else text = 0;
   if (text) text = zstrdup(text,"zdialog_text");
   zdialog_free(zd);
   return text;
}


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

//  get password input from a popup dialog - one line only
//  user input is hidden as '*' characters.
//  returned text is subject for zfree()
//  null is returned if user presses [cancel] button.

ch * zdialog_password(GtkWidget *parent, ch *title, ch *inittext)
{
   int zdialog_password_event(zdialog *zd, ch *event);

   zdialog     *zd;
   int         zstat;
   ch          *text;
   GtkWidget   *widget;

   if (! main_thread()) zappcrash("zdialog_password() called from thread");

   zd = zdialog_new(title,parent,"OK","Cancel",null);
   zdialog_add_widget(zd,"entry","text","dialog",0);
   widget = zdialog_gtkwidget(zd,"text");
   gtk_entry_set_visibility(GTK_ENTRY(widget),0);
   if (inittext) zdialog_stuff(zd,"text",inittext);

   zdialog_resize(zd,300,0);
   zdialog_set_modal(zd);
   zdialog_run(zd,zdialog_password_event,"mouse");
   zstat = zdialog_wait(zd);
   if (zstat == 1) text = (ch *) zdialog_get_data(zd,"text");
   else text = 0;
   if (text) text = zstrdup(text,"zdialog_password");
   zdialog_free(zd);
   return text;
}


int zdialog_password_event(zdialog *zd, ch *event)
{
   if (strmatch(event,"activate")) zd->zstat = 1;
   return 1;
}


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

//  Display a dialog with a message and 1-5 choice buttons.
//  Returns choice 1-N corresponding to button selected.
//  nn = zdialog_choose(parent, where, message, butt1, butt2, ... null)
//  'where' is    null:      window manager decides
//                "mouse"     put dialog at mouse position
//                "desktop"   center dialog in desktop window
//                "parent"    center dialog in parent window

int zdialog_choose(GtkWidget *parent, ch *where, ch *message, ...)
{
   zdialog     *zd;
   va_list     arglist;
   int         ii, zstat, Nbutn;
   ch          *butn[6];

   if (! main_thread()) zappcrash("zmessage_choose() called from thread");

   va_start(arglist,message);

   for (ii = 0; ii < 5; ii++)
   {
      butn[ii] = va_arg(arglist,ch *);
      if (! butn[ii] || butn[ii] == (ch *) 0x100000000) break;                   //  ARM bug
   }

   Nbutn = ii;
   if (! Nbutn) zappcrash("zdialog_choose(), no buttons");

   zd = zdialog_new("choose",parent,butn[0],butn[1],butn[2],butn[3],butn[4],null);
   zdialog_add_widget(zd,"hbox","hbmess","dialog","space=3");
   zdialog_add_widget(zd,"label","labmess","hbmess",message,"space=5");
   zdialog_set_modal(zd);
   zdialog_set_decorated(zd,0);                                                  //  24.40
   zdialog_resize(zd,200,0);
   zdialog_run(zd,null,where);
   zstat = zdialog_wait(zd);
   zdialog_free(zd);
   return zstat;
}


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

//  Display a dialog with a message and 1-5 choice buttons.
//  Returns choice 1-5 corresponding to button selected.
//  Returns -1 if cancel button [x] is selected.
//  Returns the KB character 20-127 if one is pressed.
//  nn = zdialog_choose2(parent, where, message, butt1, butt2, ... null)
//  'where' is    null:       window manager decides
//                "mouse"     put dialog at mouse position
//                "desktop"   center dialog in desktop window
//                "parent"    center dialog in parent window

int zdialog_choose2(GtkWidget *parent, ch *where, ch *message, ...)
{
   int zdialog_choose2_event(zdialog *zd, ch *event);
   int zdialog_choose2_KBevent(GtkWidget *, GdkEventKey *event, zdialog *zd);

   GtkWidget   *widget;
   zdialog     *zd;
   va_list     arglist;
   int         ii, zstat, Nbutn;
   ch          *butn[6];

   if (! main_thread()) zappcrash("zmessage_choose2() called from thread");

   va_start(arglist,message);

   for (ii = 0; ii < 5; ii++)
   {
      butn[ii] = va_arg(arglist,ch *);
      if (! butn[ii] || butn[ii] == (ch *) 0x100000000) break;                   //  ARM bug
   }

   Nbutn = ii;
   if (! Nbutn) zappcrash("zdialog_choose(), no buttons");

   zd = zdialog_new("choose",parent,butn[0],butn[1],butn[2],butn[3],butn[4],null);
   zdialog_add_widget(zd,"hbox","hbmess","dialog","space=3");
   zdialog_add_widget(zd,"label","labmess","hbmess",message,"space=5");
   zdialog_set_modal(zd);
   zdialog_resize(zd,200,0);

   widget = zd->widget[0].widget;
   G_SIGNAL(widget,"key-press-event",zdialog_choose2_KBevent,zd);

   zdialog_run(zd,zdialog_choose2_event,where);
   zstat = zdialog_wait(zd);
   zdialog_free(zd);
   return zstat;
}


//  button events and [x] event

int zdialog_choose2_event(zdialog *zd, ch *event)
{
   if (strmatch(event,"escape")) zd->zstat = -2;                                 //  escape key
   if (! zd->zstat) return 1;
   zdialog_destroy(zd);                                                          //  a button was pressed
   return 1;
}


//  KB input events

int zdialog_choose2_KBevent(GtkWidget *, GdkEventKey *event, zdialog *zd)
{
   int      KBkey = event->keyval;

   if (KBkey == GDK_KEY_Escape) {                                                //  escape key
      zdialog_destroy(zd);
      return 1;
   }

   if (KBkey >= GDK_KEY_A && KBkey <= GDK_KEY_z) {                               //  key A ... z
      zdialog_destroy(zd);
      zd->zstat = KBkey;
      return 1;
   }

   return 0;
}


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

//  popup zdialog to edit a text file
//  returns 0 if OK or user cancel, +N if error

int zdialog_edit_textfile(GtkWidget *parent, char *file)                         //  24.30
{
   zdialog  *zd;
   int      cc, err, zstat, maxcc = 1000000;                                     //  max. file size
   char     *pp, *title, buff[1000001]; 
   FILE     *fid;
   
   snprintf(buff,maxcc,"du -b %s",file);                                         //  command to get file size
   
   fid = popen(buff,"r");                                                        //  run 'du' command
   if (! fid) goto filerr;
   
   pp = fgets(buff,100,fid);                                                     //  read command output
   pclose(fid);
   if (! pp) goto filerr;

   cc = atoi(pp);                                                                //  file size
   if (cc < 0 || cc > maxcc) {                                                   //  reject file > 1 MB
      Plog(0,"file size > %d: %s \n",maxcc,file);
      return 1;
   }

   fid = fopen(file,"r");                                                        //  open file
   if (! fid) goto filerr;

   for (cc = 0; ; ) {
      pp = fgets(buff+cc,maxcc-cc,fid);                                          //  read entire file
      if (! pp) break;
      cc += strlen(pp);
   }
   
   fclose(fid);

   title = strrchr(file,'/');                                                    //  get root file name
   if (title) title++;
   else title = file;
   
   zd = zdialog_new(title,parent,"Apply"," X ",null);                            //  create text edit dialog
   zdialog_add_widget(zd,"scrwin","scroll","dialog",0,"expand");
   zdialog_add_widget(zd,"zedit","text","scroll",0,"expand");
   
   zdialog_stuff(zd,"text",buff);                                                //  stuff file text into dialog
   
   zdialog_resize(zd,500,400);
   zdialog_run(zd,0,"parent");                                                   //  run dialog

   zstat = zdialog_wait(zd);                                                     //  wait for completion
   if (zstat != 1) {
      zdialog_free(zd);                                                          //  user cancel
      return 0;
   }
   
   zdialog_fetch(zd,"text",buff,maxcc);                                          //  get edited text
   zdialog_free(zd);
   
   cc = strlen(buff);
   if (cc > maxcc) {
      Plog(0,"edited file size > %d: %s \n",maxcc,file);
      return 1;
   }
   
   fid = fopen(file,"w");
   if (! fid) goto filerr;

   err = fputs(buff,fid);
   if (err < 0 || err == EOF) goto filerr;

   err = fclose(fid);
   if (err) goto filerr;

   return 0;

filerr:
   Plog(0,"file error: %s %s \n",strerror(errno),file);
   return 1;
}


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

   popup window with scrolling text report
   line numbers and line positions are zero based

   open the report window with given title and pixel dimensions
   Fheader    add optional non-scrolling header at top of report window
   CBfunc     optional callback function:
                 CBfunc(GtkWidget *, int line, int posn, int KBkey)
    ...       optional event buttons terminated with null:
                 [OK] [Hide] [Find] [Save] [Esc] are processed here
                 others are passed to callback function (1st character)
   zdialog->zstat = 1/2 for buttons [ OK ] / [Cancel]

***/

zdialog * popup_report_open(ch *title, GtkWidget *parent, int ww, int hh,
                    int wrap, int Fheader, textwidget_callbackfunc_t CBfunc, ...)
{
   int popup_report_dialog_event(zdialog *zd, ch *event);

   va_list     arglist;
   ch          *butn[9];
   int         ii, NB;
   zdialog     *zd;
   GtkWidget   *mHead, *mText;

   va_start(arglist,CBfunc);                                                     //  get button args, if any

   for (ii = 0; ii < 9; ii++) {                                                  //  up to 9 buttons
      butn[ii] = va_arg(arglist,ch *);
      if (! butn[ii] || butn[ii] == (ch *) 0x100000000) break;                   //  ARM bug
   }

   NB = ii;                                                                      //  no. buttons

   zd = zdialog_new(title,parent,null);

   if (Fheader) {                                                                //  non-scrolling header
      zdialog_add_widget(zd,"text","header","dialog");
      zdialog_add_widget(zd,"hsep","hsep","dialog");
   }

   zdialog_add_widget(zd,"scrwin","scroll","dialog",0,"expand");                 //  scrolling text window for report

   if (wrap) zdialog_add_widget(zd,"report","text","scroll",0,"expand|wrap");    //  text > report
   else zdialog_add_widget(zd,"report","text","scroll",0,"expand");

   if (NB) {                                                                     //  optional event buttons
      zdialog_add_widget(zd,"hbox","hbbutn","dialog");
      zdialog_add_widget(zd,"label","space","hbbutn",0,"expand");
      for (ii = 0; ii < NB; ii++)
         zdialog_add_widget(zd,"button",butn[ii],"hbbutn",butn[ii],"space=5");
   }

   zdialog_resize(zd,ww,hh);                                                     //  show report dialog box
   zdialog_run(zd,popup_report_dialog_event,"save");                             //  keep window size and position

   if (Fheader) {
      mHead = zdialog_gtkwidget(zd,"header");                                    //  header initially invisible
      gtk_widget_set_visible(mHead,0);
   }

   mText = zdialog_gtkwidget(zd,"text");                                         //  report text not editable
   gtk_widget_grab_focus(mText);

   textwidget_set_eventfunc(mText,CBfunc);                                       //  set mouse/KB event function
   zd->popup_report_CB = (void *) CBfunc;

   return zd;
}


//  dialog event and completion function  [OK] [Hide] [Find] [Save] [Esc]

int popup_report_dialog_event(zdialog *zd, ch *event)
{
   textwidget_callbackfunc_t  *CBfunc;

   GtkWidget    *mText;
   static ch    findtext[40] = "";
   int          linem, line1, line2;
   zdialog      *zdf;

   if (! zdialog_valid(zd)) return 1;                                            //  report cancelled

   if (strmatch(event,"focus")) return 0;

   if (zd->zstat) {                                                              //  [x] cancel or escape, kill dialog
      zdialog_free(zd);
      return 1;
   }

   if (strmatch(event,"X")) {                                                    //  [X] close                             24.20
      zdialog_free(zd);
      return 1;
   }

   if (strmatch(event,"escape")) {                                               //  Escape key, close
      zdialog_free(zd);
      return 1;
   }

   if (strmatch(event,"Find")) {                                                 //  [Find]
      zdf = zdialog_new("find text",zd->dialog,"Find","Cancel",0);               //  popup dialog to enter text
      zdialog_add_widget(zdf,"zentry","text","dialog",findtext,"size=20");
      zdialog_run(zdf,0,"mouse");
      linem = -1;                                                                //  no match line yet
      while (true)
      {
         zdialog_wait(zdf);
         if (zdf->zstat != 1) {                                                  //  [cancel]
            zdialog_free(zdf);
            return 1;
         }
         zdf->zstat = 0;
         zdialog_fetch(zdf,"text",findtext,40);                                  //  get text
         popup_report_get_visible_lines(zd,line1,line2);                         //  lines now visible
         if (linem < 0) linem = line1;                                           //  search from 1st visible line
         linem = popup_report_find(zd,findtext,linem);                           //  search for text
         if (linem < 0) continue;                                                //  not found
         popup_report_scroll_top(zd,linem);                                      //  found, scroll to top
         linem++;                                                                //  next search from line
      }
   }

   if (strmatch(event,"Save")) {                                                 //  [Save]   save text to file
      mText = zdialog_gtkwidget(zd,"text");
      textwidget_save(mText,GTK_WINDOW(zd->parent));
      return 1;
   }

   mText = zdialog_gtkwidget(zd,"text");

   CBfunc = (textwidget_callbackfunc_t *) zd->popup_report_CB;                   //  other event
   if (CBfunc) CBfunc(mText,-1,-1,*event);                                       //  pass to callback function (1st char.)

   return 1;
}


//  write a non-scrolling header line

void popup_report_header(zdialog *zd, int bold, ch *format, ...)
{
   va_list     arglist;
   ch          message[1000];
   GtkWidget   *mHead;

   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }

   va_start(arglist,format);
   vsnprintf(message,999,format,arglist);
   va_end(arglist);

   mHead = zdialog_gtkwidget(zd,"header");
   textwidget_append(mHead,bold,message);
   gtk_widget_set_visible(mHead,1);

   return;
}


//  write a new text line at the end

void popup_report_write(zdialog *zd, int bold, ch *format, ...)
{
   va_list     arglist;
   ch          message[20000];
   GtkWidget   *mText;

   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }

   va_start(arglist,format);
   vsnprintf(message,19999,format,arglist);
   va_end(arglist);

   mText = zdialog_gtkwidget(zd,"text");
   textwidget_append(mText,bold,"%s",message);
   return;
}


//  write a new text line at the end, scroll down to end

void popup_report_write2(zdialog *zd, int bold, ch *format, ...)
{
   va_list     arglist;
   ch          message[20000];
   GtkWidget   *mText;

   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }

   va_start(arglist,format);
   vsnprintf(message,19999,format,arglist);
   va_end(arglist);

   mText = zdialog_gtkwidget(zd,"text");
   textwidget_append2(mText,bold,"%s",message);
   return;
}


//  scroll window back to top line

void popup_report_top(zdialog *zd)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_scroll(mText,0);
   return;
}


//  scroll window back to bottom line

void popup_report_bottom(zdialog *zd)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_scroll(mText,-1);
   return;
}


//  clear the report window

void popup_report_clear(zdialog *zd)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_clear(mText);
   return;
}


//  clear the report window from line to end

void popup_report_clear(zdialog *zd, int line)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_clear(mText,line);
   return;
}


//  insert a new line after a given line

void popup_report_insert(zdialog *zd, int bold, int line, ch *format, ...)
{
   va_list     arglist;
   ch          message[20000];
   GtkWidget   *mText;

   va_start(arglist,format);
   vsnprintf(message,19999,format,arglist);
   va_end(arglist);

   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }

   mText = zdialog_gtkwidget(zd,"text");
   textwidget_insert(mText,bold,line,message);
   return;
}


//  replace a given line

void popup_report_replace(zdialog *zd, int bold, int line, ch *format, ...)
{
   va_list     arglist;
   ch          message[20000];
   GtkWidget   *mText;

   va_start(arglist,format);
   vsnprintf(message,19999,format,arglist);
   va_end(arglist);

   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }

   mText = zdialog_gtkwidget(zd,"text");
   textwidget_replace(mText,bold,line,message);
   return;
}


//  delete a given line

void popup_report_delete(zdialog *zd, int line)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_delete(mText,line);
   return;
}


//  find first line of text containing characters matching input string
//  search is from line1 to end, then from 0 to line1-1
//  returns first matching line or -1 if none
//  comparison is not case sensitive


int  popup_report_find(zdialog *zd, ch *matchtext, int line1)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return 1; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   return textwidget_find(mText,matchtext,line1,1);                              //  highlight line
}


//  insert a pixbuf image after a given line

void popup_report_insert_pixbuf(zdialog *zd, int line, GdkPixbuf *pixbuf)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_insert_pixbuf(mText,line,pixbuf);
   return;
}


//  scroll to bring a given line into the report window

void popup_report_scroll(zdialog *zd, int line)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_scroll(mText,line);
   return;
}


//  scroll to bring a given line to the top of the report window

void popup_report_scroll_top(zdialog *zd, int line)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_scroll_top(mText,line);
   return;
}


//  get the range of visible lines in the report window

void popup_report_get_visible_lines(zdialog *zd, int &vtop, int &vbott)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_get_visible_lines(mText,vtop,vbott);
   return;
}


//  retrieve a given line and optionally strip the trailing \n

ch * popup_report_line(zdialog *zd, int line, int strip)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return 0; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   return textwidget_line(mText,line,strip);
}


//  retrieve the word starting at a given position in a given line

ch * popup_report_word(zdialog *zd, int line, int posn, ch *dlims, ch &end)
{
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   return textwidget_word(mText,line,posn,dlims,end);
}


//  highlight a given line of text

void popup_report_highlight_line(zdialog *zd, int line)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_highlight_line(mText,line);
   return;
}


//  highlight the text at a given position and length in a given line

void popup_report_highlight_word(zdialog *zd, int line, int posn, int cc)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_highlight_word(mText,line,posn,cc);
   return;
}


//  underline the text at a given position and length in a given line

void popup_report_underline_word(zdialog *zd, int line, int posn, int cc)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_underline_word(mText,line,posn,cc);
   return;
}


//  bold the text at a given position and length in a given line

void popup_report_bold_word(zdialog *zd, int line, int posn, int cc)
{
   if (! zdialog_valid(zd)) { Plog(1,"report cancelled \n"); return; }
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_bold_word(mText,line,posn,cc);
   return;
}


//  set font attributes for entire report                                        //  temp. kludge

void popup_report_font_attributes(zdialog *zd)
{
   if (! zdialog_valid(zd)) return;
   GtkWidget *mText = zdialog_gtkwidget(zd,"text");
   textwidget_font_attributes(mText);
   return;
}


//  close report after given seconds (OK to leave it open until user closes)
//  also connected to window destroy signal (secs = 0)

void popup_report_close(zdialog *zd, int secs)
{
   void popup_report_timeout(zdialog *zd);

   if (! zdialog_valid(zd)) return;

   if (secs < 1) {
      zdialog_free(zd);
      return;
   }

   g_timeout_add_seconds(secs,(GSourceFunc) popup_report_timeout,zd);
   return;
}


//  private function for report timeout

void popup_report_timeout(zdialog *zd)
{
   if (! zdialog_valid(zd)) return;
   zdialog_free(zd);
   return;
}


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

//  execute a shell command and show the output in a scrolling popup window
//  returns: 0 = EOF  1 = command failure

int popup_command(ch *command, int ww, int hh, GtkWidget *parent, int top)
{
   FILE        *fid;
   ch          buff[1000], *pp;
   zdialog     *zd;

   Plog(1,"run command: %s \n",command);

   zd = popup_report_open(command,parent,ww,hh,0,0,0,"Find","Save","X",0);

   fid = popen(command,"r");
   if (! fid) return 1;
   while (true) {
      pp = fgets_trim(buff,1000,fid);
      if (! pp) break;
      popup_report_write2(zd,0,"%s\n",pp);
   }
   pclose(fid);

   if (top) popup_report_top(zd);                                                //  back to top of window
   return 0;
}


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

//  Display popup message box and wait for user acknowledgement.
//  May be called from a thread.
//  Messages are presented sequentially from main() and from threads.

void zmessageACK(GtkWidget *parent, ch *format, ... )
{
   va_list        arglist;
   ch             message[2000];
   ch             *posn;
   zdialog        *zd;

   va_start(arglist,format);                                                     //  format the message
   vsnprintf(message,2000,format,arglist);
   va_end(arglist);

   Plog(1,"%s \n",message);                                                      //  output to log file

   if (! main_thread()) {                                                        //  caller is a thread
      xmessage(message);
      return;
   }

   if (parent) posn = "parent";
   else posn = "desktop";

   zd = zdialog_new("ACK",parent,"OK",null);                                     //  caller is main()
   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
   zdialog_add_widget(zd,"text","lab1","hb1",message,"space=5");                 //  24.60
   zdialog_resize(zd,200,0);
   zdialog_set_modal(zd);
   gtk_window_set_urgency_hint(GTK_WINDOW(zd->dialog),1);
   zdialog_set_decorated(zd,0);                                                  //  24.50
   zdialog_run(zd,0,posn);
   zdialog_wait(zd);
   zdialog_free(zd);
   return;
}


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

//  display message box and wait for user Yes or No response
//  returns 1 or 0

int zmessageYN(GtkWidget *parent, ch *format, ... )
{
   va_list        arglist;
   ch             message[500];
   ch             *posn;
   zdialog        *zd;
   int            zstat;

   va_start(arglist,format);
   vsnprintf(message,500,format,arglist);
   va_end(arglist);

   Plog(1,"%s \n",message);                                                      //  output to log file

   if (! main_thread()) zappcrash("zmessageYN() called from thread");

   if (parent) posn = "parent";
   else posn = "desktop";

   zd = zdialog_new("YN",parent,"Yes","No",null);
   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","lab1","hb1",message,"space=5");
   zdialog_resize(zd,200,0);
   zdialog_set_modal(zd);
   gtk_window_set_urgency_hint(GTK_WINDOW(zd->dialog),1);
   zdialog_set_decorated(zd,0);                                                  //  24.40
   zdialog_run(zd,0,posn);
   zstat = zdialog_wait(zd);
   zdialog_free(zd);
   zmainloop();                                                                  //  24.10
   if (zstat == 1) return 1;
   return 0;
}


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

//  display message until timeout (can be forever) or user cancel
//  or caller kills it with zdialog_free()
//  posn - from zdialog_run():
//    "mouse" = position at mouse
//    "desktop" = center on desktop
//    "parent" = center on parent window
//    "nn/nn" = position NW corner at relative x/y position in parent window,
//              where nn/nn is a percent 0-100 of the parent window dimensions.
//  seconds: time to keep message on screen, 0 = forever until cancelled

typedef struct {
   zdialog     *zd;
   int         uniqueID;
}  zdx_t;


zdialog * zmessage_post(GtkWidget *parent, ch *posn, int seconds, ch *format, ... )
{
   int  zmessage_post_timeout(zdx_t *zdx);

   va_list           arglist;
   ch                message[400], messagebold[460];
   static zdx_t      zdx[100];
   static int        ii = 0;
   zdialog           *zd;

   va_start(arglist,format);
   vsnprintf(message,400,format,arglist);
   va_end(arglist);

   Plog(1,"%s \n",message);                                                      //  output to log file

   if (! main_thread()) return 0;

   snprintf(messagebold,460,"<span font=\"bold\" color=\"red\">%s</span>",message);

   zd = zdialog_new("post",parent,null);
   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","lab1","hb1",messagebold,"space=5");
   zdialog_can_focus(zd,0);
   zdialog_run(zd,0,posn);                                                       //  mouse position
   zdialog_set_decorated(zd,0);                                                  //  24.40
   zdialog_present(zd);

   if (seconds) {
      if (ii < 99) ii++;                                                         //  track unique zdialogs
      else ii = 0;
      zdx[ii].zd = zd;
      zdx[ii].uniqueID = zd->uniqueID;
      g_timeout_add_seconds(seconds,(GSourceFunc) zmessage_post_timeout,&zdx[ii]);
   }

   return zd;
}


int zmessage_post_timeout(zdx_t *zdx)
{
   zdialog  *zd = zdx->zd;                                                       //  check unique zdialog active
   if (! zdialog_valid2(zd,"post")) return 0;
   if (zd->uniqueID != zdx->uniqueID) return 0;
   zdialog_free(zd);
   return 0;
}


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

//  functions to show popup text windows

namespace poptext {
   ch          *ptext = 0;
   GtkWidget   *popwin = 0;
   ch          *pcurrent = 0;
   #define GSFNORMAL GTK_STATE_FLAG_NORMAL
}


//  timer function to show popup window after a given time

int poptext_show(ch *current)
{
   using namespace poptext;

   if (current != pcurrent) return 0;
   if (popwin) gtk_widget_show_all(popwin);
   return 0;
}


//  timer function to kill popup window after a given time

int poptext_timeout(ch *current)
{
   using namespace poptext;

   if (current != pcurrent) return 0;
   if (popwin) gtk_widget_destroy(popwin);
   if (ptext) zfree(ptext);
   popwin = 0;
   ptext = 0;
   return 0;
}


//  Show a popup text message at a given absolute screen position.
//  Any prior popup will be killed and replaced.
//  If text == null, kill without replacement.
//  secs1 is time to delay before showing the popup.
//  secs2 is time to kill the popup after it is shown (0 = never).
//  This function returns immediately.

void poptext_screen(ch *text, int px, int py, float secs1, float secs2)
{
   using namespace poptext;

   GtkWidget   *label;
   int         cc, millisec1, millisec2;

   if (! main_thread()) zappcrash("poptext_screen() called from thread");

   poptext_killnow();

   pcurrent++;                                                                   //  make current != pcurrent

   if (! text) return;

   cc = strlen(text) + 4;                                                        //  construct popup window
   ptext = (ch *) zmalloc(cc,"poptext");                                         //    with caller's text
   *ptext = 0;
   strncatv(ptext,cc," ",text," ",null);                                         //  add extra spaces
   popwin = gtk_window_new(GTK_WINDOW_POPUP);
   label = gtk_label_new(ptext);
   gtk_container_add(GTK_CONTAINER(popwin),label);
   gtk_window_move(GTK_WINDOW(popwin),px,py);

   if (secs1 > 0) {                                                              //  delayed popup display
      millisec1 = secs1 * 1000;
      g_timeout_add(millisec1,(GSourceFunc) poptext_show,pcurrent);
   }
   else gtk_widget_show_all(popwin);                                             //  immediate display

   if (secs2 > 0) {                                                              //  popup kill timer
      millisec2 = (secs1 + secs2) * 1000;
      g_timeout_add(millisec2,(GSourceFunc) poptext_timeout,pcurrent);
   }

   return;
}


//  Show a popup text message at current mouse position + offsets.

void poptext_mouse(ch *text, int dx, int dy, float secs1, float secs2)
{
   using namespace poptext;

   int         mx, my;
   ch          *ptext2;
   GtkWidget   *popwin2;

   if (! main_thread()) zappcrash("poptext_mouse() called from thread");
   
   if (! text) {
      poptext_killnow();
      return;
   }

   popwin2 = popwin;
   ptext2 = ptext;
   popwin = 0;
   ptext = 0;

   gdk_device_get_position(zfuncs::mouse,0,&mx,&my);                             //  mouse screen position
   poptext_screen(text,mx+dx,my+dy,secs1,secs2);                                 //  add displacements

   zmainloop();
   
   if (popwin2) gtk_widget_destroy(popwin2);                                     //  kill prior after create new           24.60
   if (ptext2) zfree(ptext2);                                                    //  (prevent flicker) 

   return;
}


//  Show a popup text message at the given window position.

void poptext_window(GtkWindow *win, ch *text, int dx, int dy, float secs1, float secs2)
{
   int      px, py;

   if (! main_thread()) zappcrash("poptext_window() called from thread");

   if (! text) {
      poptext_killnow();
      return;
   }
   gtk_window_get_position(win,&px,&py);
   poptext_screen(text,px+dx,py+dy,secs1,secs2);
   return;
}


//  Show a popup text message at the given widget position.

void poptext_widget(GtkWidget *widget, ch *text, int dx, int dy, float secs1, float secs2)
{
   GdkWindow   *win;
   int         px, py;

   if (! main_thread()) zappcrash("poptext_widget() called from thread");

   if (! text) {
      poptext_killnow();
      return;
   }
   win = gtk_widget_get_window(widget);
   gdk_window_get_origin(win,&px,&py);
   poptext_screen(text,px+dx,py+dy,secs1,secs2);
   return;
}


//  kill popup window unconditionally

int poptext_killnow()
{
   using namespace poptext;

   if (popwin) gtk_widget_destroy(popwin);
   if (ptext) zfree(ptext);
   popwin = 0;
   ptext = 0;
   return 0;
}


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

//  popup a picklist at mouse position, return user choice

int      picklist_busy = 0;
ch       *picklist_choice = 0;

ch * popup_picklist(GtkWidget *parent, ch **list, ch **desc, int Np)
{
   void  popup_picklist_func(GtkWidget *, ch *menu);

   GtkWidget   *popmenu;

   popmenu = create_popmenu();

   if (desc) {
      for (int ii = 0; ii < Np; ii++)
         add_popmenu_item(popmenu,list[ii],popup_picklist_func,0,desc[ii]);
   }
   else {
      for (int ii = 0; ii < Np; ii++)
         add_popmenu_item(popmenu,list[ii],popup_picklist_func,0,0);
   }

   picklist_busy = 1;
   picklist_choice = 0;

   popup_menu(parent,popmenu);

   while (picklist_busy) {
      if (! gtk_widget_get_mapped(popmenu)) picklist_busy = 0;
      zmainsleep(0.1);
   }

   g_object_ref_sink(popmenu);
   return picklist_choice;
}


void popup_picklist_func(GtkWidget *popmenu, ch *menu)
{
   picklist_busy = 0;
   picklist_choice = menu;
   return;
}


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

    File chooser dialog for one or more files

    Action:  "file"            select an existing file
             "files"           select multiple existing files
             "save"            select an existing or new file
             "folder"          select existing folder
             "folders"         select multiple existing folders
             "create folder"   select existing or new folder

    hidden   if > 0, add button to toggle display of hidden files
             optional, default = 0

    Returns a list of filespecs terminated with null.
    Memory for returned list and returned files are subjects for zfree();

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

//  version for 1 file only: file, save, folder, create folder
//  returns one filespec or null
//  returned file is subject for zfree()

ch * zgetfile(ch *title, GtkWindow *parent, ch *action, ch *initfile, int hidden)
{
   if (! strmatchV(action,"file","save","folder","create folder",null))
      zappcrash("zgetfile() call error: %s",action);

   ch   **flist = zgetfiles(title,parent,action,initfile,hidden);
   if (! flist) return 0;
   ch   *file = *flist;
   zfree(flist);
   return file;
}


//  version for 2 or more files
//  returns a list of filespecs (ch **) terminated with null
//  returns null if canceled by user

ch ** zgetfiles(ch *title, GtkWindow *parent, ch *action, ch *initfile, int hidden)
{
   void zgetfile_preview(GtkWidget *dialog, GtkWidget *pvwidget);                //  private functions
   int  zgetfile_KBkey(GtkWidget *dialog, GdkEventKey *event, int &fcdes);
   void zgetfile_newfolder(GtkFileChooser *dialog, void *);

   GtkFileChooserAction fcact = GTK_FILE_CHOOSER_ACTION_OPEN;

   GtkWidget   *dialog;
   PIXBUF      *thumbnail;
   GtkWidget   *pvwidget = gtk_image_new();
   GSList      *gslist = 0;
   ch          *button1 = 0, *buttxx = 0;
   ch          *pdir, *pfile;
   int         ii, err, NF, setfname = 0;
   int         fcstat, bcode = 0, hide = 1;
   int         fcdes = 0;
   ch          *file1, *file2, **flist = 0;
   STATB       statB;

   if (strmatch(action,"file")) {
      fcact = GTK_FILE_CHOOSER_ACTION_OPEN;
      button1 = "choose file";
   }

   else if (strmatch(action,"files")) {
      fcact = GTK_FILE_CHOOSER_ACTION_OPEN;
      button1 = "choose files";
   }

   else if (strmatch(action,"save")) {
      fcact = GTK_FILE_CHOOSER_ACTION_SAVE;
      button1 = "Save";
      setfname = 1;
   }

   else if (strmatch(action,"folder")) {
      fcact = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
      button1 = "choose folder";
   }

   else if (strmatch(action,"folders")) {
      fcact = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
      button1 = "choose folders";
   }

   else if (strmatch(action,"create folder")) {
      fcact = GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER;
      button1 = "create folder";
      setfname = 1;
   }

   else zappcrash("zgetfiles() call error: %s",action);

   if (hidden) {
      buttxx = "hidden";
      bcode = 103;
   }

   dialog = gtk_file_chooser_dialog_new(title, parent, fcact,                    //  create file selection dialog
                              button1, GTK_RESPONSE_ACCEPT,                      //  parent added
                              "Cancel", GTK_RESPONSE_CANCEL,
                              buttxx, bcode, null);

   gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(dialog),pvwidget);

   G_SIGNAL(dialog,"update-preview",zgetfile_preview,pvwidget);                  //  create preview for selected file
   G_SIGNAL(dialog,"key-press-event",zgetfile_KBkey,&fcdes);                     //  respond to special KB keys

   gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_MOUSE);                //  put dialog at mouse position
   gtk_file_chooser_set_show_hidden(GTK_FILE_CHOOSER(dialog),0);                 //  default: no show hidden

   if (strmatch(action,"save"))                                                  //  overwrite confirmation
      gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog),1);

   if (strmatch(action,"files") || strmatch(action,"folders"))
      gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog),1);          //  select multiple files or folders

   if (initfile) {                                                               //  pre-select filespec
      err = stat(initfile,&statB);
      if (err) {
         pdir = zstrdup(initfile,"zgetfiles");                                   //  non-existent file
         pfile = strrchr(pdir,'/');
         if (pfile && pfile > pdir) {
            *pfile++ = 0;                                                        //  set folder name
            gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog),pdir);
         }
         if (setfname) {                                                         //  set new file name
            if (! pfile) pfile = (ch *) initfile;
            gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog),pfile);
         }
         zfree(pdir);
      }
      else if (S_ISREG(statB.st_mode))                                           //  select given file
         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog),initfile);
      else if (S_ISDIR(statB.st_mode))                                           //  select given folder
         gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog),initfile);
   }

   if (initfile) {
      thumbnail = get_thumbnail(initfile,256);                                   //  preview for initial file
      if (thumbnail) {
         gtk_image_set_from_pixbuf(GTK_IMAGE(pvwidget),thumbnail);
         gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog),1);
         g_object_unref(thumbnail);
      }
      else gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog),0);
   }

   gtk_widget_show_all(dialog);

   while (true)
   {
      fcstat = gtk_dialog_run(GTK_DIALOG(dialog));                               //  run dialog, get status button

      if (fcstat == 103) {                                                       //  show/hide hidden files
         hide = 1 - hide;
         gtk_file_chooser_set_show_hidden(GTK_FILE_CHOOSER(dialog),hide);
         continue;
      }

      else if (fcstat == GTK_RESPONSE_ACCEPT)
      {
         gslist = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog));
         if (! gslist) continue;

         NF = g_slist_length(gslist);                                            //  no. selected files
         flist = (ch **) zmalloc((NF+1)*sizeof(ch *),"zgetfiles");               //  allocate returned list

         for (ii = 0; ii < NF; ii++)
         {                                                                       //  process selected files
            file1 = (ch *) g_slist_nth_data(gslist,ii);
            file2 = zstrdup(file1,"zgetfiles");                                  //  re-allocate memory
            flist[ii] = file2;
            g_free(file1);
         }
         flist[ii] = 0;                                                          //  EOL marker
         break;
      }

      else break;                                                                //  user bailout
   }

   if (gslist) g_slist_free(gslist);                                             //  return selected file(s)
   if (! fcdes) gtk_widget_destroy(dialog);                                      //  destroy if not already
   return flist;
}


//  zgetfile private function - get preview images for image files

void zgetfile_preview(GtkWidget *dialog, GtkWidget *pvwidget)
{
   PIXBUF      *thumbnail;
   ch          *filename;

   filename = gtk_file_chooser_get_preview_filename(GTK_FILE_CHOOSER(dialog));

   if (! filename) {
      gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog),0);
      return;
   }

   thumbnail = get_thumbnail(filename,256);                                      //  256x256 pixels
   g_free(filename);

   if (thumbnail) {
      gtk_image_set_from_pixbuf(GTK_IMAGE(pvwidget),thumbnail);
      gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog),1);
      g_object_unref(thumbnail);
   }
   else gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog),0);

   return;
}


//  zgetfile private function - KB functions

int zgetfile_KBkey(GtkWidget *dialog, GdkEventKey *event, int &fcdes)
{
   int KBkey = event->keyval;

   if (KBkey == GDK_KEY_F1) {                                                    //  F1 = help
      KBevent(event);
      return 1;
   }

   if (KBkey == GDK_KEY_Escape) {                                                //  escape = cancel
      gtk_widget_destroy(dialog);
      fcdes = 1;
      return 1;
   }

   return 0;
}


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

//  select a folder (or create a new folder)
//  returns location (pathname) of selected or created folder.
//  returned location is subject for zfree().

ch * zgetfolder(ch *title, GtkWindow *parent, ch *initfolder)
{
   GtkWidget      *dialog;
   GtkFileChooser *chooser;
   int      nn;
   ch       *pp1, *pp2 = null;

   dialog = gtk_file_chooser_dialog_new(title, parent,
                  GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
                  "Cancel", GTK_RESPONSE_CANCEL,
                  "Open", GTK_RESPONSE_ACCEPT, NULL);

   chooser = GTK_FILE_CHOOSER(dialog);
   gtk_file_chooser_set_filename(chooser, initfolder);

   nn = gtk_dialog_run(GTK_DIALOG(dialog));
   if (nn != GTK_RESPONSE_ACCEPT) {
      gtk_widget_destroy(dialog);
      return null;
   }

   pp1 = gtk_file_chooser_get_filename(chooser);
   if (pp1) {
      pp2 = zstrdup(pp1,"zgetfolder");
      g_free(pp1);
   }

   gtk_widget_destroy(dialog);
   return pp2;
}


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

   print_image_file(GtkWidget *parent, ch *imagefile)

   Print an image file using the printer, paper, orientation,
   margins, and scale set by the user.

   HPLIP problem: Setting paper size was made less flexible.
   GtkPrintSettings paper size must agree with the one in the current
   printer setup. This can only be set in the printer setup dialog, not
   in the application. Also the print size (width, height) comes from
   the chosen paper size and cannot be changed in the application.
   Print margins can be changed to effect printing a smaller or shifted
   image on a larger paper size.

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

namespace print_image
{
   #define MM GTK_UNIT_MM
   #define INCH GTK_UNIT_INCH
   #define PRINTOP   GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG
   #define PORTRAIT  GTK_PAGE_ORIENTATION_PORTRAIT
   #define LANDSCAPE GTK_PAGE_ORIENTATION_LANDSCAPE
   #define QUALITY   GTK_PRINT_QUALITY_HIGH

   GtkWidget                  *parent = 0;
   GtkPageSetup               *priorpagesetup = 0;
   GtkPageSetup               *pagesetup;
   GtkPrintSettings           *printsettings = 0;
   GtkPrintOperation          *printop;
   GtkPageOrientation         orientation = PORTRAIT;
   PIXBUF                     *pixbuf;
   ch                         *printer = 0;
   int                        landscape = 0;                                     //  true if landscape
   double                     width = 21.0, height = 29.7;                       //  paper size, CM (default A4 portrait)
   double                     margins[4] = { 0.5, 0.5, 0.5, 0.5 };               //  margins, CM (default 0.5)
   double                     imagescale = 100;                                  //  image print scale, percent
   double                     pwidth, pheight;                                   //  printed image size

   int   page_setup();
   int   margins_setup();
   int   margins_dialog_event(zdialog *zd, ch *event);
   void  get_printed_image_size();
   void  print_page(GtkPrintOperation *, GtkPrintContext *, int page);
}


//  user callable function to set paper, margins, scale, and then print

void print_image_file(GtkWidget *pwin, ch *imagefile)
{
   using namespace print_image;

   GtkPrintOperationResult  printstat;
   GError   *gerror = 0;
   int      err;

   parent = pwin;                                                                //  save parent window

   pixbuf = gdk_pixbuf_new_from_file(imagefile,&gerror);                         //  read image file
   if (! pixbuf) {
      zmessageACK(mainwin,gerror->message);
      return;
   }

   err = page_setup();                                                           //  select size and orientation
   if (err) return;

   err = margins_setup();                                                        //  set margins and scale
   if (err) return;

   printop = gtk_print_operation_new();                                          //  print operation
   gtk_print_operation_set_default_page_setup(printop,pagesetup);
   gtk_print_operation_set_print_settings(printop,printsettings);
   gtk_print_operation_set_n_pages(printop,1);

   g_signal_connect(printop,"draw-page",G_CALLBACK(print_page),0);               //  start print
   printstat = gtk_print_operation_run(printop,PRINTOP,0,0);

   if (printstat == GTK_PRINT_OPERATION_RESULT_ERROR) {
      gtk_print_operation_get_error(printop,&gerror);
      zmessageACK(mainwin,gerror->message);
   }

   g_object_unref(printop);
   return;
}


//  draw the graphics for the print page
//  rescale with cairo

void print_image::print_page(GtkPrintOperation *printop, GtkPrintContext *printcontext, int page)
{
   using namespace print_image;

   cairo_t           *cairocontext;
   double            iww, ihh, pww, phh, scale;

   pww = gtk_print_context_get_width(printcontext);                              //  print context size, pixels
   phh = gtk_print_context_get_height(printcontext);

   iww = gdk_pixbuf_get_width(pixbuf);                                           //  original image size
   ihh = gdk_pixbuf_get_height(pixbuf);

   scale = pww / iww;                                                            //  rescale to fit page
   if (phh / ihh < scale) scale = phh / ihh;

   cairocontext = gtk_print_context_get_cairo_context(printcontext);             //  use cairo to rescale
   cairo_translate(cairocontext,0,0);
   cairo_scale(cairocontext,scale,scale);
   gdk_cairo_set_source_pixbuf(cairocontext,pixbuf,0,0);
   cairo_paint(cairocontext);

   return;
}


//   Do a print paper format selection, after which the page width, height
//   and orientation are available to the caller. Units are CM.
//   (paper width and height are reversed for landscape orientation)

int print_image::page_setup()
{
   using namespace print_image;

   ch     printsettingsfile[200], pagesetupfile[200];

   snprintf(printsettingsfile,200,"%s/printsettings",zhomedir);
   snprintf(pagesetupfile,200,"%s/pagesetup",zhomedir);

   if (! printsettings) {                                                        //  start with prior print settings
      printsettings = gtk_print_settings_new_from_file(printsettingsfile,0);
      if (! printsettings)
         printsettings = gtk_print_settings_new();
   }

   if (! priorpagesetup) {                                                       //  start with prior page setup
      priorpagesetup = gtk_page_setup_new_from_file(pagesetupfile,0);
      if (! priorpagesetup)
         priorpagesetup = gtk_page_setup_new();
   }

   pagesetup = gtk_print_run_page_setup_dialog                                   //  select printer, paper, orientation
            (GTK_WINDOW(parent),priorpagesetup,printsettings);                   //  user cancel cannot be detected

   g_object_unref(priorpagesetup);                                               //  save for next call
   priorpagesetup = pagesetup;

   orientation = gtk_print_settings_get_orientation(printsettings);              //  save orientation
   if (orientation == LANDSCAPE) landscape = 1;
   else landscape = 0;

   gtk_print_settings_set_quality(printsettings,QUALITY);                        //  set high quality 300 dpi
   gtk_print_settings_set_resolution(printsettings,300);

   gtk_print_settings_to_file(printsettings,printsettingsfile,0);                //  save print settings to file
   gtk_page_setup_to_file(pagesetup,pagesetupfile,0);                            //  save print settings to file

   return 0;
}


//   Optionally set the print margins and print scale.
//   If canceled the margins are zero (or printer-dependent minimum)
//   and the scale is 100% (fitting the paper and margins).

int print_image::margins_setup()
{
   using namespace print_image;

   zdialog     *zd;
   int         zstat;

/***
       __________________________________________________
      | [x] (-) [_]   Margins                            |
      |                                                  |
      |  Margins   Top      Bottom     Left     Right    |
      |     CM   [ 0.50 ]  [ 0.50 ]  [ 0.50 ]  [ 0.50 ]  |
      |    Inch  [ 0.20 ]  [ 0.20 ]  [ 0.20 ]  [ 0.20 ]  |
      |                                                  |
      |  image scale [ 80 ] percent                      |
      |                                                  |
      |  image  width  height                            |
      |    CM    xx.x   xx.x                             |
      |   Inch   xx.x   xx.x                             |
      |                                 [ OK ] [cancel]  |
      |__________________________________________________|

***/

   zd = zdialog_new("Margins",parent,"OK","Cancel",null);
   zdialog_add_widget(zd,"hbox","hbmlab","dialog");

   zdialog_add_widget(zd,"vbox","vbmarg","hbmlab",0,"homog|space=3");
   zdialog_add_widget(zd,"vbox","vbtop","hbmlab",0,"homog|space=3");
   zdialog_add_widget(zd,"vbox","vbbottom","hbmlab",0,"homog|space=3");
   zdialog_add_widget(zd,"vbox","vbleft","hbmlab",0,"homog|space=3");
   zdialog_add_widget(zd,"vbox","vbright","hbmlab",0,"homog|space=3");

   zdialog_add_widget(zd,"label","labmarg","vbmarg","Margins","space=5");
   zdialog_add_widget(zd,"label","labcm","vbmarg","CM","space=5");
   zdialog_add_widget(zd,"label","labinch","vbmarg","Inch","space=5");

   zdialog_add_widget(zd,"label","labtop","vbtop","Top");
   zdialog_add_widget(zd,"zspin","mtopcm","vbtop","0|10|0.01|0");
   zdialog_add_widget(zd,"zspin","mtopin","vbtop","0|4|0.01|0");

   zdialog_add_widget(zd,"label","labbot","vbbottom","Bottom");
   zdialog_add_widget(zd,"zspin","mbottcm","vbbottom","0|10|0.01|0");
   zdialog_add_widget(zd,"zspin","mbottin","vbbottom","0|4|0.01|0");

   zdialog_add_widget(zd,"label","lableft","vbleft","Left");
   zdialog_add_widget(zd,"zspin","mleftcm","vbleft","0|10|0.01|0");
   zdialog_add_widget(zd,"zspin","mleftin","vbleft","0|4|0.01|0");

   zdialog_add_widget(zd,"label","labright","vbright","Right");
   zdialog_add_widget(zd,"zspin","mrightcm","vbright","0|10|0.01|0");
   zdialog_add_widget(zd,"zspin","mrightin","vbright","0|4|0.01|0");

   zdialog_add_widget(zd,"hbox","hbscale","dialog",0,"space=5");
   zdialog_add_widget(zd,"label","labscale","hbscale","image scale","space=5");
   zdialog_add_widget(zd,"zspin","scale","hbscale","5|100|1|100");
   zdialog_add_widget(zd,"label","labpct","hbscale","percent","space=5");

   zdialog_add_widget(zd,"hbox","hbsize","dialog",0,"space=3");
   zdialog_add_widget(zd,"vbox","vbunit","hbsize",0,"space=5");
   zdialog_add_widget(zd,"vbox","vbwidth","hbsize",0,"space=5");
   zdialog_add_widget(zd,"vbox","vbheight","hbsize",0,"space=5");

   zdialog_add_widget(zd,"label","space","vbunit","Image");
   zdialog_add_widget(zd,"label","labcm","vbunit","CM");
   zdialog_add_widget(zd,"label","labinch","vbunit","Inch");

   zdialog_add_widget(zd,"label","labwidth","vbwidth","Width");
   zdialog_add_widget(zd,"label","labwcm","vbwidth","xx.x");
   zdialog_add_widget(zd,"label","labwin","vbwidth","xx.x");

   zdialog_add_widget(zd,"label","labheight","vbheight","Height");
   zdialog_add_widget(zd,"label","labhcm","vbheight","xx.x");
   zdialog_add_widget(zd,"label","labhin","vbheight","xx.x");

   zdialog_load_inputs(zd);                                                      //  recall prior settings

   zdialog_fetch(zd,"mtopcm",margins[0]);
   zdialog_fetch(zd,"mbottcm",margins[1]);
   zdialog_fetch(zd,"mleftcm",margins[2]);
   zdialog_fetch(zd,"mrightcm",margins[3]);
   zdialog_fetch(zd,"scale",imagescale);

   get_printed_image_size();
   zdialog_stuff(zd,"labwcm",pwidth,"%.2f");                                     //  update image size in dialog
   zdialog_stuff(zd,"labhcm",pheight,"%.2f");
   zdialog_stuff(zd,"labwin",pwidth/2.54,"%.2f");
   zdialog_stuff(zd,"labhin",pheight/2.54,"%.2f");

   gtk_page_setup_set_top_margin(pagesetup,10*margins[0],MM);                    //  set page margins
   gtk_page_setup_set_bottom_margin(pagesetup,10*margins[1],MM);                 //  (cm to mm units)
   gtk_page_setup_set_left_margin(pagesetup,10*margins[2],MM);
   gtk_page_setup_set_right_margin(pagesetup,10*margins[3],MM);
   gtk_print_settings_set_scale(printsettings,imagescale);                       //  set image print scale %

   zdialog_run(zd,margins_dialog_event,"parent");                                //  run dialog
   zstat = zdialog_wait(zd);                                                     //  wait for completion
   zdialog_free(zd);                                                             //  kill dialog

   if (zstat == 1) return 0;
   return 1;
}


//  dialog event function
//  save user margin and scale changes
//  recompute print image size

int print_image::margins_dialog_event(zdialog *zd, ch *event)
{
   using namespace print_image;

   double   temp;

   if (strmatch(event,"escape")) zd->zstat = -2;                                 //  escape key

   if (strmatch(event,"mtopcm")) {                                               //  get cm inputs and set inch values
      zdialog_fetch(zd,"mtopcm",margins[0]);
      zdialog_stuff(zd,"mtopin",margins[0]/2.54);
   }

   if (strmatch(event,"mbottcm")) {
      zdialog_fetch(zd,"mbottcm",margins[1]);
      zdialog_stuff(zd,"mbottin",margins[1]/2.54);
   }

   if (strmatch(event,"mleftcm")) {
      zdialog_fetch(zd,"mleftcm",margins[2]);
      zdialog_stuff(zd,"mleftin",margins[2]/2.54);
   }

   if (strmatch(event,"mrightcm")) {
      zdialog_fetch(zd,"mrightcm",margins[3]);
      zdialog_stuff(zd,"mrightin",margins[3]/2.54);
   }

   if (strmatch(event,"mtopin")) {                                               //  get inch inputs and set cm values
      zdialog_fetch(zd,"mtopin",temp);
      margins[0] = temp * 2.54;
      zdialog_stuff(zd,"mtopcm",margins[0]);
   }

   if (strmatch(event,"mbottin")) {
      zdialog_fetch(zd,"mbottin",temp);
      margins[1] = temp * 2.54;
      zdialog_stuff(zd,"mbottcm",margins[1]);
   }

   if (strmatch(event,"mleftin")) {
      zdialog_fetch(zd,"mleftin",temp);
      margins[2] = temp * 2.54;
      zdialog_stuff(zd,"mleftcm",margins[2]);
   }

   if (strmatch(event,"mrightin")) {
      zdialog_fetch(zd,"mrightin",temp);
      margins[3] = temp * 2.54;
      zdialog_stuff(zd,"mrightcm",margins[3]);
   }

   zdialog_fetch(zd,"scale",imagescale);                                         //  get image scale

   get_printed_image_size();
   zdialog_stuff(zd,"labwcm",pwidth,"%.2f");                                     //  update image size in dialog
   zdialog_stuff(zd,"labhcm",pheight,"%.2f");
   zdialog_stuff(zd,"labwin",pwidth/2.54,"%.2f");
   zdialog_stuff(zd,"labhin",pheight/2.54,"%.2f");

   gtk_page_setup_set_top_margin(pagesetup,10*margins[0],MM);                    //  set page margins
   gtk_page_setup_set_bottom_margin(pagesetup,10*margins[1],MM);                 //  (cm to mm units)
   gtk_page_setup_set_left_margin(pagesetup,10*margins[2],MM);
   gtk_page_setup_set_right_margin(pagesetup,10*margins[3],MM);
   gtk_print_settings_set_scale(printsettings,imagescale);                       //  set image print scale %

   return 1;
}


//  compute printed image size based on paper size,
//    orientation, margins, and scale (percent)

void print_image::get_printed_image_size()
{
   using namespace print_image;

   double   iww, ihh, pww, phh, scale;

   pww = 0.1 * gtk_page_setup_get_paper_width(pagesetup,MM);                     //  get paper size
   phh = 0.1 * gtk_page_setup_get_paper_height(pagesetup,MM);                    //  (mm to cm units)

   pww = pww - margins[2] - margins[3];                                          //  reduce for margins
   phh = phh - margins[0] - margins[1];

   pww = pww / 2.54 * 300;                                                       //  convert to dots @ 300 dpi
   phh = phh / 2.54 * 300;

   iww = gdk_pixbuf_get_width(pixbuf);                                           //  original image size, pixels
   ihh = gdk_pixbuf_get_height(pixbuf);

   scale = pww / iww;                                                            //  rescale image to fit page
   if (phh / ihh < scale) scale = phh / ihh;

   scale = scale * 0.01 * imagescale;                                            //  adjust for user scale setting

   pwidth = iww * scale / 300 * 2.54;                                            //  dots to cm
   pheight = ihh * scale / 300 * 2.54;

   return;
}


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

//  connect a user callback function to a drag-drop source widget

void drag_drop_source(GtkWidget *widget, drag_drop_source_func ufunc)
{
   void drag_drop_source2(GtkWidget *, GdkDragContext *, void *ufunc);
   void drag_drop_source3(GtkWidget *, GdkDragContext *, GtkSelectionData *, int, int, void *ufunc);

   gtk_drag_source_set(widget,GDK_BUTTON1_MASK,null,0,GDK_ACTION_COPY);
   gtk_drag_source_add_text_targets(widget);
   gtk_drag_source_add_image_targets(widget);
   G_SIGNAL(widget, "drag-begin", drag_drop_source2, ufunc);
   G_SIGNAL(widget, "drag-data-get", drag_drop_source3, ufunc);
   return;
}


//  private function for "drag-begin" signal

void drag_drop_source2(GtkWidget *widget, GdkDragContext *context, void *ufunc)
{
   drag_drop_source_func  *ufunc2;

   GdkPixbuf   *pixbuf;
   GError      *gerror = 0;
   ch          *file = 0;

   ufunc2 = (drag_drop_source_func *) ufunc;
   file = ufunc2();
   if (! file) goto cancel;

   pixbuf = gdk_pixbuf_new_from_file_at_size(file,128,128,&gerror);
   if (! pixbuf) {
      if (gerror) Plog(0,"%s \n",gerror->message);
      return;
   }

   gtk_drag_set_icon_pixbuf(context,pixbuf,64,64);                               //  hot spot is middle of image
   return;

cancel:
   Plog(2,"drag canceled \n");
   return;
}


//  private function for "drag-data-get" signal

void drag_drop_source3(GtkWidget *widget, GdkDragContext *context, GtkSelectionData *data, int, int, void *ufunc)
{
   drag_drop_source_func  *ufunc2;

   ch        *file = 0;
// ch        *files[2] = { file, null };

   ufunc2 = (drag_drop_source_func *) ufunc;
   file = ufunc2();
   if (! file) goto cancel;
   gtk_selection_data_set_text(data,file,-1);                                    //  drops text
// gtk_selection_data_set_uris(data,files);                                      //  does nothing     FIXME
   return;

cancel:
   Plog(2,"drag canceled \n");
   return;
}


//  connect a user callback function to a drag-drop destination widget

void drag_drop_dest(GtkWidget *widget, drag_drop_dest_func *ufunc)
{
   int  drag_drop_dest2(GtkWidget *, GdkDragContext *, int, int, void *, int, int time, void *);
   int  drag_drop_dest3(GtkWidget *, void *, int, int, int, void *);
   int  drag_drop_dest4(GtkWidget *, void *, int, void *);

   gtk_drag_dest_set(widget,GTK_DEST_DEFAULT_ALL,null,0,GDK_ACTION_COPY);
   gtk_drag_dest_add_text_targets(widget);
   G_SIGNAL(widget, "drag-data-received", drag_drop_dest2, ufunc);
   G_SIGNAL(widget, "drag-motion", drag_drop_dest3, ufunc);
   G_SIGNAL(widget, "drag-leave", drag_drop_dest4, ufunc);

   return;
}


//  private function for "drag-data-received" signal
//  get dropped file, clean escapes, pass to user function
//  passed filespec is subject for zfree()

int drag_drop_dest2(GtkWidget *, GdkDragContext *context, int mpx, int mpy, void *sdata, int, int time, void *ufunc)
{
   ch  * drag_drop_unescape(ch *escaped_string);
   drag_drop_dest_func  *ufunc2;

   ch       *text, *text2, *file, *file2;
   int      cc;

   text = (ch *) gtk_selection_data_get_data((GtkSelectionData *) sdata);

   ufunc2 = (drag_drop_dest_func *) ufunc;

   if (strstr(text,"file://"))                                                   //  text is a filespec
   {
      file = zstrdup(text+7,"drag_drop");                                        //  get rid of junk added by GTK
      cc = strlen(file);
      while (file[cc-1] < ' ') cc--;
      file[cc] = 0;
      file2 = drag_drop_unescape(file);                                          //  clean %xx escapes from Nautilus
      zfree(file);
      ufunc2(mpx,mpy,file2);                                                     //  pass file to user function
   }

   else                                                                          //  text is text
   {
      text2 = zstrdup(text,"drag_drop");
      ufunc2(mpx,mpy,text2);
   }

   gtk_drag_finish(context,1,0,time);
   return 1;
}


//  private function for "drag-motion" signal
//  pass mouse position to user function during drag

int drag_drop_dest3(GtkWidget *, void *, int mpx, int mpy, int, void *ufunc)
{
   drag_drop_dest_func  *ufunc2;
   ufunc2 = (drag_drop_dest_func *) ufunc;
   if (! ufunc2) return 0;
   ufunc2(mpx,mpy,null);
   return 0;
}


//  private function for "drag-leave" signal
//  pass mouse position (0,0) to user function

int  drag_drop_dest4(GtkWidget *, void *, int, void *ufunc)
{
   drag_drop_dest_func  *ufunc2;
   ufunc2 = (drag_drop_dest_func *) ufunc;
   if (! ufunc2) return 0;
   ufunc2(0,0,null);
   return 0;
}


//  private function
//  Clean %xx escapes from strange Nautilus drag-drop file names

ch * drag_drop_unescape(ch *inp)
{
   int  drag_drop_convhex(ch ch1);

   ch       inch, *out, *outp;
   int      nib1, nib2;

   out = (ch *) zmalloc(strlen(inp)+1,"drag_drop");
   outp = out;

   while ((inch = *inp++))
   {
      if (inch == '%')
      {
         nib1 = drag_drop_convhex(*inp++);
         nib2 = drag_drop_convhex(*inp++);
         *outp++ = nib1 << 4 | nib2;
      }
      else *outp++ = inch;
   }

   *outp = 0;
   return out;
}


//  private function - convert character 0-F to number 0-15

int drag_drop_convhex(ch ch1)
{
   if (ch1 >= '0' && ch1 <= '9') return  ch1 - '0';
   if (ch1 >= 'A' && ch1 <= 'F') return  ch1 - 'A' + 10;
   if (ch1 >= 'a' && ch1 <= 'f') return  ch1 - 'a' + 10;
   return ch1;
}


/********************************************************************************
   Miscellaneous GDK/GTK functions
*********************************************************************************/

//  Get thumbnail image for given image file.
//  Returned thumbnail belongs to caller: g_object_unref() is necessary.

PIXBUF * get_thumbnail(ch *fpath, int size)
{
   PIXBUF      *thumbpxb;
   GError      *gerror = 0;
   int         err;
   ch          *bpath;
   STATB       statB;

   err = stat(fpath,&statB);                                                     //  fpath status info
   if (err) return 0;

   if (S_ISDIR(statB.st_mode)) {                                                 //  if folder, return folder image
      bpath = (ch *) zmalloc(500,"get_thumbnail");
      *bpath = 0;
      strncatv(bpath,499,zimagedir,"/folder.png",null);
      thumbpxb = gdk_pixbuf_new_from_file_at_size(bpath,size,size,&gerror);
      zfree(bpath);
      return thumbpxb;
   }

   thumbpxb = gdk_pixbuf_new_from_file_at_size(fpath,size,size,&gerror);
   return thumbpxb;                                                              //  return pixbuf to caller
}


//  make a cursor from a graphic file in application folder
//  (see initz_appfiles()).

GdkCursor * zmakecursor(ch *imagefile)
{
   GError         *gerror = 0;
   PIXBUF         *pixbuf;
   GdkDisplay     *display;
   GdkCursor      *cursor = 0;
   ch             imagepath[200];

   display = gdk_display_get_default();
   *imagepath = 0;
   strncatv(imagepath,199,zimagedir,"/",imagefile,null);
   pixbuf = gdk_pixbuf_new_from_file(imagepath,&gerror);
   if (pixbuf && display)
      cursor = gdk_cursor_new_from_pixbuf(display,pixbuf,0,0);
   else Plog(0,"*** %s \n",gerror->message);
   return cursor;
}


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

   PIXBUF * gdk_pixbuf_rotate(PIXBUF *pixbuf, float angle, int acolor)

   Rotate a pixbuf through an arbitrary angle (degrees).

   The returned image has the same size as the original, but the
   pixbuf envelope is increased to accommodate the rotated original
   (e.g. a 100x100 pixbuf rotated 45 deg. needs a 142x142 pixbuf).

   Pixels added around the rotated image have all RGB values = acolor.
   Angle is in degrees. Positive direction is clockwise.
   Pixbuf must have 8 bits per channel and 3 or 4 channels.
   Loss of resolution is about 1/2 pixel.
   Speed is about 28 million pixels/sec. on 3.3 GHz CPU.
   (e.g. a 10 megapix image needs about 0.36 seconds)

   NULL is returned if the function fails for one of the following:
      - pixbuf not 8 bits/channel or < 3 channels
      - unable to create output pixbuf (lack of memory?)

   Algorithm:
      create output pixbuf big enough for rotated input pixbuf
      compute coefficients for affine transform
      loop all output pixels (px2,py2)
         get corresp. input pixel (px1,py1) using affine transform
         if outside of pixbuf
            output pixel = black
            continue
         for 4 input pixels based at (px0,py0) = (int(px1),int(py1))
            compute overlap (0 to 1) with (px1,py1)
            sum RGB values * overlap
         output aggregate RGB to pixel (px2,py2)

   Benchmark: rotate 7 megapixel image 10 degrees
               0.31 secs.  3.3 GHz Core i5

***/

PIXBUF * gdk_pixbuf_rotate(PIXBUF *pixbuf1, float angle, int acolor)
{
   typedef unsigned ch  *pixel;                                                  //  3 RGB values, 0-255 each

   PIXBUF      *pixbuf2;
   GDKCOLOR    color;

   int      nch, nbits, alpha;
   int      ww1, hh1, rs1, ww2, hh2, rs2;
   int      px2, py2, px0, py0;
   pixel    ppix1, ppix2, pix0, pix1, pix2, pix3;
   float    px1, py1;
   float    f0, f1, f2, f3, red, green, blue, tran = 0;
   float    a, b, d, e, ww15, hh15, ww25, hh25;
   float    PI = 3.141593;

   nch = gdk_pixbuf_get_n_channels(pixbuf1);
   nbits = gdk_pixbuf_get_bits_per_sample(pixbuf1);
   if (nch < 3) return 0;                                                        //  must have 3+ channels (colors)
   if (nbits != 8) return 0;                                                     //  must be 8 bits per channel

   color = gdk_pixbuf_get_colorspace(pixbuf1);                                   //  get input pixbuf1 attributes
   alpha = gdk_pixbuf_get_has_alpha(pixbuf1);
   ww1 = gdk_pixbuf_get_width(pixbuf1);
   hh1 = gdk_pixbuf_get_height(pixbuf1);
   rs1 = gdk_pixbuf_get_rowstride(pixbuf1);

   while (angle < -180) angle += 360;                                            //  normalize, -180 to +180
   while (angle > 180) angle -= 360;
   angle = angle * PI / 180;                                                     //  radians, -PI to +PI

   if (fabsf(angle) < 0.001) {
      pixbuf2 = gdk_pixbuf_copy(pixbuf1);                                        //  angle is zero within my precision
      return pixbuf2;
   }

   ww2 = int(ww1*fabsf(cosf(angle)) + hh1*fabsf(sinf(angle)));                   //  rectangle containing rotated image
   hh2 = int(ww1*fabsf(sinf(angle)) + hh1*fabsf(cosf(angle)));

   pixbuf2 = gdk_pixbuf_new(color,alpha,nbits,ww2,hh2);                          //  create output pixbuf2
   if (! pixbuf2) return 0;
   rs2 = gdk_pixbuf_get_rowstride(pixbuf2);

   ppix1 = gdk_pixbuf_get_pixels(pixbuf1);                                       //  input pixel array
   ppix2 = gdk_pixbuf_get_pixels(pixbuf2);                                       //  output pixel array

   ww15 = 0.5 * ww1;
   hh15 = 0.5 * hh1;
   ww25 = 0.5 * ww2;
   hh25 = 0.5 * hh2;

   a = cosf(angle);                                                              //  affine transform coefficients
   b = sinf(angle);
   d = - sinf(angle);
   e = cosf(angle);

   for (py2 = 0; py2 < hh2; py2++)                                               //  loop through output pixels
   for (px2 = 0; px2 < ww2; px2++)
   {
      px1 = a * (px2 - ww25) + b * (py2 - hh25) + ww15;                          //  (px1,py1) = corresponding
      py1 = d * (px2 - ww25) + e * (py2 - hh25) + hh15;                          //    point within input pixels

      px0 = int(px1);                                                            //  pixel containing (px1,py1)
      py0 = int(py1);

      if (px1 < 0 || px0 >= ww1-1 || py1 < 0 || py0 >= hh1-1) {                  //  if outside input pixel array
         pix2 = ppix2 + py2 * rs2 + px2 * nch;                                   //    output is acolor
         pix2[0] = pix2[1] = pix2[2] = acolor;
         continue;
      }

      pix0 = ppix1 + py0 * rs1 + px0 * nch;                                      //  4 input pixels based at (px0,py0)
      pix1 = pix0 + rs1;
      pix2 = pix0 + nch;
      pix3 = pix0 + rs1 + nch;

      f0 = (px0+1 - px1) * (py0+1 - py1);                                        //  overlap of (px1,py1)
      f1 = (px0+1 - px1) * (py1 - py0);                                          //    in each of the 4 pixels
      f2 = (px1 - px0) * (py0+1 - py1);
      f3 = (px1 - px0) * (py1 - py0);

      red =   f0 * pix0[0] + f1 * pix1[0] + f2 * pix2[0] + f3 * pix3[0];         //  sum the weighted inputs
      green = f0 * pix0[1] + f1 * pix1[1] + f2 * pix2[1] + f3 * pix3[1];
      blue =  f0 * pix0[2] + f1 * pix1[2] + f2 * pix2[2] + f3 * pix3[2];
      if (alpha)
       tran = f0 * pix0[3] + f1 * pix1[3] + f2 * pix2[3] + f3 * pix3[3];         //  4th color = alpha

      if (red == acolor && green == acolor && blue == acolor) {                  //  avoid acolor in image
         if (blue == 0) blue = 1;
         else blue--;
      }

      pix2 = ppix2 + py2 * rs2 + px2 * nch;                                      //  output pixel
      pix2[0] = int(red);
      pix2[1] = int(green);
      pix2[2] = int(blue);
      if (alpha) pix2[3] = int(tran);
   }

   return pixbuf2;
}


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

//  strip the alpha channel from a pixbuf
//  returns 0 if no alpha channel or fatal error

PIXBUF * gdk_pixbuf_stripalpha(PIXBUF *pixbuf1)
{
   PIXBUF      *pixbuf2;
   GDKCOLOR    color;
   int         ww, hh, rs1, rs2;
   uint8       *ppix1, *ppix2, *pix1, *pix2;
   int         nch, ac;
   int         px, py;

   ac = gdk_pixbuf_get_has_alpha(pixbuf1);
   if (! ac) return 0;
   nch = gdk_pixbuf_get_n_channels(pixbuf1);
   color = gdk_pixbuf_get_colorspace(pixbuf1);
   ww = gdk_pixbuf_get_width(pixbuf1);
   hh = gdk_pixbuf_get_height(pixbuf1);

   pixbuf2 = gdk_pixbuf_new(color,0,8,ww,hh);                                    //  create output pixbuf2
   if (! pixbuf2) return 0;

   ppix1 = gdk_pixbuf_get_pixels(pixbuf1);                                       //  input pixel array
   ppix2 = gdk_pixbuf_get_pixels(pixbuf2);                                       //  output pixel array
   rs1 = gdk_pixbuf_get_rowstride(pixbuf1);
   rs2 = gdk_pixbuf_get_rowstride(pixbuf2);

   for (py = 0; py < hh; py++)
   {
      pix1 = ppix1 + py * rs1;
      pix2 = ppix2 + py * rs2;

      for (px = 0; px < ww; px++)
      {
         memcpy(pix2,pix1,nch-1);
         pix1 += nch;
         pix2 += nch-1;
      }
   }

   return pixbuf2;
}


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

//  Create a pixbuf containing text with designated font and attributes.
//  Text is white on black. Widget is ultimate display destination.

PIXBUF * text_pixbuf(ch *text, ch *font, int fontsize, GtkWidget *widget)
{
   ch                      font2[60];
   PangoFontDescription    *pfont;
   PangoLayout             *playout;
   cairo_surface_t         *surface;
   cairo_t                 *cr;
   PIXBUF                  *pixbuf;
   uint8                   *pixels, *cairo_data, *cpix, *pix2;
   int                     ww, hh, rs, px, py;

   if (! font) font = zfuncs::appfont;                                           //  default font

   snprintf(font2,60,"%s %d",font,fontsize);                                     //  combine font and size

   pfont = pango_font_description_from_string(font2);                            //  make layout with text
   playout = gtk_widget_create_pango_layout(widget,text);
   pango_layout_set_font_description(playout,pfont);

   pango_layout_get_pixel_size(playout,&ww,&hh);
   ww += 2 + 0.2 * fontsize;                                                     //  compensate bad font metrics
   hh += 2 + 0.1 * fontsize;

   surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24,ww,hh);               //  cairo output image
   cr = cairo_create(surface);
   pango_cairo_show_layout(cr,playout);                                          //  write text layout to image

   cairo_data = cairo_image_surface_get_data(surface);                           //  get text image pixels

   pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB,0,8,ww,hh);
   rs = gdk_pixbuf_get_rowstride(pixbuf);
   pixels = gdk_pixbuf_get_pixels(pixbuf);

   for (py = 0; py < hh; py++)                                                   //  copy text image to PXB
   for (px = 0; px < ww; px++)
   {
      cpix = cairo_data + 4 * (ww * py + px);
      pix2 = pixels + py * rs + px * 3;
      pix2[0] = pix2[1] = pix2[2] = cpix[3];
   }

   pango_font_description_free(pfont);                                           //  free resources
   g_object_unref(playout);
   cairo_destroy(cr);
   cairo_surface_destroy(surface);

   return pixbuf;
}


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

//  move the mouse pointer to given position in given window
//  widget must be realized

int move_pointer(GtkWidget *widget, int px, int py)
{
   int         rpx, rpy;
   GdkWindow   *window;

   window = gtk_widget_get_window(widget);
   gdk_window_get_root_coords(window,px,py,&rpx,&rpy);
   gdk_device_warp(mouse,screen,rpx,rpy);
   return 1;
}


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

//  move a window to the mouse position
//  widget is a GtkWindow, which may or may not be realized

void window_to_mouse(GtkWidget *window)
{
   using namespace zfuncs;

   int      px, py;

   gdk_device_get_position(mouse,&screen,&px,&py);                               //  get mouse position
   gtk_window_move(GTK_WINDOW(window),px,py);
   return;
}