File: f.meta.cc

package info (click to toggle)
fotoxx 18.07.2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 14,648 kB
  • sloc: cpp: 71,278; makefile: 113; xml: 28
file content (9961 lines) | stat: -rw-r--r-- 403,371 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
/********************************************************************************

   Fotoxx      edit photos and manage collections

   Copyright 2007-2018 Michael Cornelison
   source code URL: https://kornelix.net
   contact: kornelix@posteo.de

   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.

*********************************************************************************

   Fotoxx image editor - image metadata functions.

   View and edit metadata
   ----------------------
   select_meta_keys           dialog to select metadata items
   m_meta_view_main           metadata short report
   m_meta_view_all            report all metadata
   m_meta_edit_main           primary edit metadata dialog
   manage_tags                maintain list of defined tags
   m_meta_edit_any            dialog to fetch and save any image metadata by name
   m_meta_delete              dialog to delete any image file metadata by name
   m_meta_captions            write captions and comments at top of current image
   m_batch_tags               batch add and delete tags for selected image files
   m_batch_rename_tags        convert tag names for all image files using a from-to list
   m_batch_photo_date_time    change or shift photo date/time
   m_batch_change_metadata    add/change or delete metadata for selected image files
   m_batch_report_metadata    batch metadata report to text file
   m_batch_geotags            add given geotag to selected set of images

   Image search utilities
   ----------------------
   m_meta_places_dates        find images by location and date range
   m_meta_timeline            find images by year and month
   m_search_images            find images using any metadata and/or file names

   pdate_metadate             convert yyyy-mm-dd to yyyymmdd
   ptime_metatime             convert hh:mm[:ss] to hhmmss
   pdatetime_metadatetime     convert yyyy-mm-dd hh:mm[:ss] to yyyymmddhhmmss
   metadate_pdate             convert yyyymmddhhmmss to yyyy-mm-dd and hh:mm:ss
   datetimeOK                 validate yyyy-mm-dd hh:mm[:ss] date/time

   add_tag                    add tag to a tag list
   add_tag_fotoxx             add tag "fotoxx" for edited image (for f_save())
   set_meta_wwhh              set image width/height metadata
   del_tag                    remove tag from a tag list
   add_recentag               add tag to recent tags list, remove oldest if needed
   load_deftags               load defined tags list from tags file and image index
   save_deftags               save defined tags list to tags file
   find_deftag                check if given tag is in defined tags list
   add_deftag                 add new tag to defined tags list or change category
   del_deftag                 remove tag from defined tags list
   deftags_stuff              stuff defined tags into dialog text widget
   defcats_stuff              stuff defined categories into dialog combobox widget
   tag_orphans                report tags defined and not used in any image file

   load_filemeta              load image file metadata into memory (indexed data only)
   save_filemeta              save metadata to image file EXIF and to image index
   update_image_index         update index data for current image file
   delete_image_index         delete index record for deleted image file

   web_geocode                web service to map location to earth coordinates
   init_geolocs               load geolocations table from image index file
   find_location              find locations matching partial location/country input
   put_geolocs                put new location data in geolocations table
   validate_latlong           validate earth coordinates data
   earth_distance             compute km distance between two earth coordinates
   get_gallerymap             get map coordinates for current gallery files
   m_set_map_markers          set map markers: all images or current gallery

   Geotag mapping (W view)
   -----------------------
   m_load_filemap             load a geographic map file chosen by user
   filemap_position           convert earth coordinates to map pixel position
   filemap_coordinates        convert map pixel position to earth coordinates
   filemap_paint_dots         paint red dots on map where images are located
   filemap_mousefunc          respond to mouse movement and left clicks on map
   find_filemap_images        find images within range of geolocation
   free_filemap               free huge memory for filemap image

   Geotag mapping (M view)
   -----------------------
   m_netmap_source            choose net map source
   m_load_netmap              initialize net map
   netmap_paint_dots          paint red dots on map where images are located
   m_netmap_zoomin            zoom net map in on image location
   netmap_zoomto              callable with input zoom level
   netmapscale                get net map scale at zoom level
   netmap_mousefunc           respond to clicks on net map
   find_netmap_images         find images
   m_netmap_locs              save and recall net map locs (center, zoom level)

   EXIF store and retrieve
   -----------------------
   exif_get                   get image metadata from list of keys
   exif_put                   update image metadata from list of keys and data
   exif_copy                  copy metadata from file to file, with revisions
   exif_server                start exiftool server process, send data requests
   exif_tagdate               yyyy:mm:dd hh:mm:ss to yyyymmddhhmmss
   tag_exifdate               yyyymmddhhmmss to yyyy:mm:dd hh:mm:ss

   Image index functions
   ---------------------
   get_xxrec                  get image index record for image file
   get_xxrec_min              get minimal index record data for gallery window
   put_xxrec                  add or update index record for an image file
   read_xxrec_seq             read all index records sequentially, one per call
   write_xxrec_seq            write all index records sequentially

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

#define EX extern                                                                //  enable extern declarations
#include "fotoxx.h"                                                              //  (variables in fotoxx.h are refs)

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

char  *pdate_metadate(cchar *pdate);                                             //  "yyyy-mm-dd" to "yyyymmdd"
char  *ptime_metatime(cchar *ptime);                                             //  "hh:mm[:ss]" to "hhmmss"
char  *pdatetime_metadatetime(cchar *pdatetime);                                 //  yyyy-mm-dd hh:mm[:ss] to yyyymmddhhmmss
void  manage_tags();                                                             //  manage tags dialog
int   add_tag(char *tag, char *taglist, int maxcc);                              //  add tag if unique and enough space
int   del_tag(char *tag, char *taglist);                                         //  remove tag from tag list
int   add_recentag(char *tag);                                                   //  add tag to recent tags, keep recent
void  load_deftags();                                                            //  tags_defined file >> tags_deftags[]
void  save_deftags();                                                            //  tags_deftags[] >> defined_tags file
int   find_deftag(char *tag);                                                    //  find tag in tags_deftags[]
int   add_deftag(char *catg, char *tag);                                         //  add tag to tags_deftags[]
int   del_deftag(char *tag);                                                     //  remove tag from tags_deftags[]
void  deftags_stuff(zdialog *zd, cchar *catg);                                   //  tags_deftags[] >> zd widget deftags
void  defcats_stuff(zdialog *zd);                                                //  defined categories >> " widget defcats

cchar *web_geocode(zdialog *zd);                                                 //  find earth coordinates via web service
int   init_geolocs();                                                            //  load geolocs table from index file
int   geolocs_compare(cchar *rec1, cchar *rec2);                                 //  compare geolocs recs location
int   find_location(zdialog *zd);                                                //  find locations matching partial inputs
int   put_geolocs(zdialog *zd);                                                  //  Update geolocations table in memory
int   validate_latlong(char *lati, char *longi, float &flat, float &flong);      //  convert and validate earth coordinates
float earth_distance(float lat1, float long1, float lat2, float long2);          //  compute distance from earth coordinates
int   get_gallerymap();                                                          //  get map coordinates for gallery files
void  netmap_zoomto(float flati, float flongi, int zoomlev);                     //  zoom net map to location and zoom level
float netmapscale(int zoomlev, float flat, float flong);                         //  net map scale at given zoom and location


namespace meta_names 
{
   char     meta_pdate[16];                                                      //  image (photo) date, yyyymmddhhmmss
   char     meta_rating[4];                                                      //  image rating in stars, "0" to "5"
   char     meta_wwhh[16];                                                       //  image width/height, "NNNNxNNNN"
   char     meta_tags[tagFcc];                                                   //  tags for current image file
   char     meta_comments[exif_maxcc];                                           //  image comments            expanded
   char     meta_caption[exif_maxcc];                                            //  image caption
   char     meta_location[100], meta_country[100];                               //  geolocs: location, country
   char     meta_lati[20], meta_longi[20];                                       //  geolocs: earth coordinates (-123.4567)

   char     p_meta_pdate[16];                                                    //  previous file metadata
   char     p_meta_rating[4];
   char     p_meta_tags[tagFcc];
   char     p_meta_comments[exif_maxcc];
   char     p_meta_caption[exif_maxcc];
   char     p_meta_location[100], p_meta_country[100];
   char     p_meta_lati[20], p_meta_longi[20];
   
   char     *xmeta_data[Mxmeta];                                                 //  indexed metadata (xmeta_key[])     18.01

   char     *tags_deftags[maxtagcats];                                           //  defined tags: catg: tag1, ... tagN,
   char     tags_recentags[tagRcc] = "";                                         //  recently added tags list

   char     keyname[40], keydata[exif_maxcc];

   zdialog     *zd_mapgeotags = 0;                                               //  zdialog wanting geotags via map click

   struct geolocs_t {                                                            //  geolocations table, memory DB
      char     *location, *country;                                              //  maps locations <-> earth coordinates
      float    flati, flongi;                                                    //    "  float, 7 digit precision
   };

   geolocs_t   **geolocs = 0;                                                    //  geolocs table
   int         Ngeolocs = 0;                                                     //  size of geolocations table

   struct gallerymap_t {                                                         //  geocoordinates for gallery files
      char     *file;
      float    flati, flongi;
   };

   gallerymap_t   *gallerymap = 0;
   int            Ngallerymap = 0;
}


using namespace meta_names;


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

//  Dialog to select metadata items (for index, view, report).
//  The item list is an input and an output. EOL marker is null.
//  Fexclude: exclude items indexed by default.
//  returns 0/1 = no changes / changes made

namespace select_meta_keys_names
{
   GtkWidget   *mtext1, *mtext2;
}   

int select_meta_keys(char *itemlist[], int Fexclude)
{
   using namespace select_meta_keys_names;

   void  select_meta_keys_clickfunc1(GtkWidget *, int line, int pos, int kbkey);
   void  select_meta_keys_clickfunc2(GtkWidget *, int line, int pos, int kbkey);

   zdialog     *zd;
   char        itemfile[200], buff[100], buff2[100], *pp;
   FILE        *fid;
   int         zstat, ii;

/***
       __________________________________________________________
      |                  Add Metadata Items                      |
      |                                                          |
      |       click to select            click to unselect       |
      |  _________________________   __________________________  |
      | | Orientation             | |                          | |
      | | Rotation                | |                          | |
      | | Exposure Time           | |                          | |
      | | Aperture                | |                          | |
      | |   ...                   | |                          | |
      | | Other Item ...          | |                          | |
      | |_________________________| |__________________________| |
      |                                                          |
      |                                          [done] [cancel] |
      |__________________________________________________________|

***/

   zd = zdialog_new(E2X("Add Metadata Items"),Mwin,Bdone,Bcancel,null);

   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"expand");
   zdialog_add_widget(zd,"vbox","vb1","hb1",0,"expand|space=3");
   zdialog_add_widget(zd,"label","lab1","vb1",E2X("click to select"));
   zdialog_add_widget(zd,"scrwin","scroll1","vb1",0,"expand");
   zdialog_add_widget(zd,"text","mtext1","scroll1",0,"expand");

   zdialog_add_widget(zd,"vbox","vb2","hb1",0,"expand|space=3");
   zdialog_add_widget(zd,"label","lab2","vb2",E2X("click to unselect"));
   zdialog_add_widget(zd,"scrwin","scroll2","vb2",0,"expand");
   zdialog_add_widget(zd,"text","mtext2","scroll2",0,"expand");

   mtext1 = zdialog_widget(zd,"mtext1");
   textwidget_clear(mtext1);

   mtext2 = zdialog_widget(zd,"mtext2");
   textwidget_clear(mtext2);

   snprintf(itemfile,200,"%s/metadata_short_list",get_zhomedir());               //  metadata item list >> left widget
   fid = fopen(itemfile,"r");
   if (! fid) {
      zmessageACK(Mwin,"%s \n %s",itemfile,strerror(errno));
      return 0;
   }

   while (true) {
      pp = fgets_trim(buff,100,fid,1);
      if (! pp) break;
      if (*pp <= ' ') continue;
      if (Fexclude) {
         strCompress(buff2,buff);
         if (strmatch(buff2,iptc_keywords_key)) continue;                        //  exclude items indexed and          18.01
         if (strmatch(buff2,iptc_rating_key)) continue;                          //    reported by default
         if (strmatch(buff2,exif_wwhh_key)) continue;                            //                                     18.07
         if (strmatch(buff2,exif_date_key)) continue;
         if (strmatch(buff2,exif_comment_key)) continue;
         if (strmatch(buff2,exif_usercomment_key)) continue;
         if (strmatch(buff2,iptc_caption_key)) continue;
         if (strmatch(buff2,exif_city_key)) continue;
         if (strmatch(buff2,exif_country_key)) continue;
         if (strmatch(buff2,exif_lati_key)) continue;
         if (strmatch(buff2,exif_longi_key)) continue;
         if (strmatch(buff2,"Location")) continue;                               //  synonym for "City"
      }
      textwidget_append(mtext1,0,"%s\n",buff);
   }
   
   textwidget_append(mtext1,0,"%s\n","Other Item ...");                          //  append "Other Item ..."

   fclose(fid);
   
   for (ii = 0; ii < Mxmeta; ii++)                                               //  input item list >> right widget    18.01
   {
      if (! itemlist[ii]) break;
      textwidget_append(mtext2,0,"%s\n",itemlist[ii]);
   }

   textwidget_set_callbackfunc(mtext1,select_meta_keys_clickfunc1);              //  connect mouse clicks
   textwidget_set_callbackfunc(mtext2,select_meta_keys_clickfunc2);

   zdialog_resize(zd,500,300);
   zdialog_set_modal(zd);                                                        //  17.08
   zdialog_run(zd,0,"parent");                                                   //  run dialog
   zstat = zdialog_wait(zd);                                                     //  wait for dialog completion

   if (zstat != 1) {                                                             //  canceled
      zdialog_free(zd);
      return 0;                                                                  //  return "no change"
   }

   for (ii = 0; ii < Mxmeta; ii++) {                                             //  free input list
      if (! itemlist[ii]) break;
      zfree(itemlist[ii]);
   }

   for (ii = 0; ii < Mxmeta; ii++) {                                             //  replace input list with output     18.01
      pp = textwidget_line(mtext2,ii,1);                                         //  remove trailing \n
      if (! pp || ! *pp) break;
      itemlist[ii] = zstrdup(pp);
   }

   itemlist[ii] = 0;                                                             //  mark EOL

   zdialog_free(zd);
   return 1;                                                                     //  return "changes made"              18.01
}


//  get clicked tag name from input list and insert into output list

void select_meta_keys_clickfunc1(GtkWidget *widget, int line, int pos, int kbkey) 
{
   using namespace select_meta_keys_names;

   char     *pp;
   
   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   pp = textwidget_line(widget,line,1);                                          //  get clicked line, highlight
   if (! pp || ! *pp) return;
   textwidget_highlight_line(widget,line);
   
   if (strmatch(pp,"Other Item ...")) {                                          //  get manually input metadata name
      pp = zdialog_text(Mwin,"metadata item name",0);
      if (! pp) return;
      strCompress(pp);                                                           //  remove blanks
      textwidget_append2(mtext2,0,"%s\n",pp);                                    //  append to output list
      zfree(pp);
      return;
   }

   strCompress(pp);                                                              //  remove blanks
   textwidget_append2(mtext2,0,"%s\n",pp);                                       //  append to output list
   return;
}


//  get clicked tag name from output list and remove it

void select_meta_keys_clickfunc2(GtkWidget *widget, int line, int pos, int kbkey) 
{
   using namespace select_meta_keys_names;

   char     *pp1, *pp2;
   int      ii, Nitems = 0;
   char     *itemlist[Mxmeta];
   
   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   pp1 = textwidget_line(widget,line,1);                                         //  get clicked line
   if (! pp1 || ! *pp1) return;
   
   for (line = 0; ; line++)
   {                                                                             //  read and save all lines
      pp2 = textwidget_line(mtext2,line,1);
      if (! pp2 || ! *pp2) break;
      if (strmatch(pp2,pp1)) continue;                                           //  skip clicked line
      itemlist[Nitems] = zstrdup(pp2);
      if (++Nitems == Mxmeta) break;
   }
   
   textwidget_clear(mtext2);                                                     //  clear output list
   
   for (ii = 0; ii < Nitems; ii++)                                               //  write new output list
   {
      textwidget_append(mtext2,0,"%s\n",itemlist[ii]);
      zfree(itemlist[ii]);
   }

   return;
}


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

//  menu function and popup dialog to show EXIF/IPTC data
//  window is updated when navigating to another image

int   metadata_report_type = 1;


//  called by f_open() if zdexifview is defined

void meta_view(int type)
{
   if (type && metadata_report_type != type) {
      if (zdexifview) zdialog_free(zdexifview);
      zdexifview = 0;
   }

   if (type) metadata_report_type = type;

   if (metadata_report_type == 2)
      m_meta_view_all(0,0);
   else 
      m_meta_view_main(0,0);
   return;
}


//  menu function - short report

void m_meta_view_main(GtkWidget *, cchar *menu)
{
   int   meta_view_dialog_event(zdialog *zd, cchar *event);

   #define     NK 20
   cchar       *keyname[NK] = { "ImageSize", "FileSize", exif_date_key, "FileModifyDate", "Make", "Model",
                              exif_focal_length_key, "ExposureTime", "FNumber", "ISO",
                              exif_city_key, exif_country_key, exif_lati_key, exif_longi_key,
                              iptc_keywords_key, iptc_rating_key, iptc_caption_key, exif_comment_key,
                              exif_usercomment_key, exif_editlog_key };
   char        *keyval[NK];

   char           chsec[12], **text;
   static char    *file, *filen, *chsize;
   float          fsize, fsec;
   int            err, ii, nn;
   cchar          *textdelims = "!-,.:;?/)}]";
   cchar          *editdelims = ":|,";
   GtkWidget      *widget;

   FILE           *fid;
   int            nkx;
   char           *keynamex[NK], *keyvalx[NK];
   char           extras_file[200], buff[100], *pp;

   F1_help_topic = "view_metadata";
   
   if (metadata_report_type != 1) {
      if (zdexifview) zdialog_free(zdexifview);
      zdexifview = 0;
      metadata_report_type = 1;
   }
   
   if (clicked_file) {                                                           //  use clicked file if present        18.01
      file = clicked_file;
      clicked_file = 0;
   }
   else if (curr_file) file = zstrdup(curr_file);
   else return;
   
   if (FGWM == 'G') gallery(0,"paint",-1);                                       //  if gallery view, repaint

   if (! zdexifview)                                                             //  popup dialog if not already
   {
      zdexifview = zdialog_new(E2X("View Metadata"),Mwin,E2X("Extras"),Bcancel,null);
      zdialog_add_widget(zdexifview,"scrwin","scroll","dialog",0,"expand");
      zdialog_add_widget(zdexifview,"text","exifdata","scroll",0,"expand");
      zdialog_resize(zdexifview,550,350);
      zdialog_run(zdexifview,meta_view_dialog_event,"save");
   }

   widget = zdialog_widget(zdexifview,"exifdata");
   textwidget_clear(widget);

   err = exif_get(file,keyname,keyval,NK);
   if (err) {
      zmessageACK(Mwin,"exif failure");
      return;
   }

   filen = strrchr(file,'/');                                                    //  get file name without directory
   if (filen) filen++;
   else filen = file;

   fsize = 0;
   if (keyval[1]) fsize = atof(keyval[1]);                                       //  get file size in B/KB/MB units
   chsize = formatKBMB(fsize,3);

   if (keyval[2] && strlen(keyval[2]) > 19) keyval[2][19] = 0;                   //  truncate dates to yyyy-mm-dd hh:mm:ss
   if (keyval[3] && strlen(keyval[3]) > 19) keyval[3][19] = 0;
   
   pp = keyval[2];
   if (pp && strlen(pp) > 4 && pp[4] == ':') pp[4] = '-';                        //  change yyyy:mm:dd to yyyy-mm-dd
   if (pp && strlen(pp) > 7 && pp[7] == ':') pp[7] = '-';
   pp = keyval[3];
   if (pp && strlen(pp) > 4 && pp[4] == ':') pp[4] = '-';
   if (pp && strlen(pp) > 7 && pp[7] == ':') pp[7] = '-';

   textwidget_append(widget,0,"File        %s \n",filen);
   textwidget_append(widget,0,"Size        %s  %s \n",keyval[0],chsize);
   textwidget_append(widget,0,"Dates       photo: %s  file: %s \n",keyval[2],keyval[3]);

   if (keyval[4] || keyval[5])
      textwidget_append(widget,0,"Camera      %s  %s \n",keyval[4],keyval[5]);

   if (keyval[6] || keyval[7] || keyval[8] || keyval[9])                         //  photo exposure data
   {
      strcpy(chsec,"null");
      if (keyval[7]) {
         fsec = atof(keyval[7]);                                                 //  convert 0.008 seconds to 1/125 etc.
         if (fsec > 0 && fsec <= 0.5) {
            fsec = 1/fsec;
            snprintf(chsec,12,"1/%.0f",fsec);
         }
         else if (fsec > 0)
            snprintf(chsec,12,"%.0f",fsec);
      }
      textwidget_append(widget,0,"Exposure    %s mm  %s sec  F%s  ISO %s \n",
                        keyval[6],chsec,keyval[8],keyval[9]);
   }

   if (keyval[10] || keyval[11] || keyval[12] || keyval[13])                     //  geotag data
      textwidget_append(widget,0,"Location    %s %s  %s %s \n",
                    keyval[10],keyval[11],keyval[12],keyval[13]);

   if (keyval[14])
      textwidget_append(widget,0,"Keywords    %s \n",keyval[14]);                //  tags

   if (keyval[15])                                                               //  rating
      textwidget_append(widget,0,"Rating      %s \n",keyval[15]);

   if (keyval[16]) {                                                             //  caption-abstract
      nn = breakup_text(keyval[16],text,textdelims,40,60);
      textwidget_append(widget,0,"Caption     %s \n",text[0]);
      for (ii = 1; ii < nn; ii++)
         textwidget_append(widget,0,"            %s \n",text[ii]);
      for (ii = 0; ii < nn; ii++)
         zfree(text[ii]);
      zfree(text);
   }

   if (keyval[17]) {                                                             //  comment
      nn = breakup_text(keyval[17],text,textdelims,40,60);
      textwidget_append(widget,0,"Comment     %s \n",text[0]);
      for (ii = 1; ii < nn; ii++)
         textwidget_append(widget,0,"            %s \n",text[ii]);
      for (ii = 0; ii < nn; ii++)
         zfree(text[ii]);
      zfree(text);
   }

   if (keyval[18]) {                                                             //  usercomment
      nn = breakup_text(keyval[18],text,textdelims,40,60);
      textwidget_append(widget,0,"UserComment %s \n",text[0]);
      for (ii = 1; ii < nn; ii++)
         textwidget_append(widget,0,"            %s \n",text[ii]);
      for (ii = 0; ii < nn; ii++)
         zfree(text[ii]);
      zfree(text);
   }

   if (keyval[19]) {                                                             //  edit history log
      nn = breakup_text(keyval[19],text,editdelims,40,60);
      textwidget_append(widget,0,"Edits       %s \n",text[0]);
      for (ii = 1; ii < nn; ii++)
         textwidget_append(widget,0,"            %s \n",text[ii]);
      for (ii = 0; ii < nn; ii++)
         zfree(text[ii]);
      zfree(text);
   }

   for (ii = 0; ii < NK; ii++)                                                   //  free memory
      if (keyval[ii]) zfree(keyval[ii]);

   //  append extra report items if any      

   snprintf(extras_file,200,"%s/metadata_view_extra",get_zhomedir()); 
   fid = fopen(extras_file,"r"); 
   if (! fid) goto finished;                                                     //  no extras file

   for (nkx = 0; nkx < NK; nkx++) {                                              //  get list of user extras
      pp = fgets_trim(buff,100,fid,1);
      if (! pp) break;
      strCompress(pp);
      if (*pp <= ' ') { nkx--; continue; }
      keynamex[nkx] = zstrdup(pp);
   }
   fclose(fid);
   
   if (nkx == 0) goto finished;                                                  //  empty file
      
   err = exif_get(file,(cchar **) keynamex,keyvalx,nkx);                         //  get all items at once
   if (err) {
      zmessageACK(Mwin,"exif failure");
      goto finished;
   }

   textwidget_append(widget,0,"\n");                                             //  blank line
   
   for (ii = 0; ii < nkx; ii++)                                                  //  report user extra items
      if (keyvalx[ii]) 
         textwidget_append(widget,0,"%-24s : %s \n",keynamex[ii],keyvalx[ii]);
   
   for (ii = 0; ii < nkx; ii++) {                                                //  free memory
      if (keynamex[ii]) zfree(keynamex[ii]);
      if (keyvalx[ii]) zfree(keyvalx[ii]);
   }

finished:
   zfree(file);                                                                  //  18.01
   return;
}


//  menu function - long report

void m_meta_view_all(GtkWidget *, cchar *menu)
{
   int   meta_view_dialog_event(zdialog *zd, cchar *event);

   char           *file, *buff;
   int            contx = 0;
   GtkWidget      *widget;

   F1_help_topic = "view_metadata";

   if (metadata_report_type != 2) {
      if (zdexifview) zdialog_free(zdexifview);
      zdexifview = 0;
      metadata_report_type = 2;
   }

   if (clicked_file) {                                                           //  use clicked file if present        18.01
      file = clicked_file;
      clicked_file = 0;
   }
   else if (curr_file) file = zstrdup(curr_file);
   else return;

   if (FGWM == 'G') gallery(0,"paint",-1);                                       //  if gallery view, repaint

   if (! zdexifview)                                                             //  popup dialog if not already
   {
      zdexifview = zdialog_new(E2X("View Metadata"),Mwin,Bcancel,null);
      zdialog_add_widget(zdexifview,"scrwin","scroll","dialog",0,"expand");
      zdialog_add_widget(zdexifview,"text","exifdata","scroll",0,"expand|wrap");
      zdialog_resize(zdexifview,700,700);
      zdialog_run(zdexifview,meta_view_dialog_event,"save");
   }

   widget = zdialog_widget(zdexifview,"exifdata");
   gtk_text_view_set_editable(GTK_TEXT_VIEW(widget),0);                          //  disable widget editing
   gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(widget),GTK_WRAP_NONE);             //  disable text wrap
   textwidget_clear(widget);

   snprintf(command,CCC,"exiftool -s -e \"%s\" ",file);

   while ((buff = command_output(contx,command))) {                              //  run command, output into window
      textwidget_append(widget,0,"%s\n",buff);
      zfree(buff);
   }

   command_status(contx);

   zfree(file);                                                                  //  18.01
   return;
}


//  dialog event and completion callback function

int meta_view_dialog_event(zdialog *zd, cchar *event)
{
   char     filex[200];
   int      zstat, ii, jj;
   char     *itemlist[Mxmeta], *pp, buff[100];
   FILE     *fid;
   
   zstat = zd->zstat;
   if (! zstat) return 1;                                                        //  wait for completion

   zdialog_free(zd);                                                             //  kill dialog
   zdexifview = 0;

   if (metadata_report_type != 1) return 1;                                      //  not short report
   if (zstat != 1) return 1;                                                     //  not [extras] button

   snprintf(filex,200,"%s/metadata_view_extra",get_zhomedir());                  //  [extras] button
   
   itemlist[0] = 0;                                                              //  extra metadata items = empty

   fid = fopen(filex,"r");                                                       //  read file of extra metadata items  18.01
   if (fid) {
      for (ii = jj = 0; ii < Mxmeta; ii++) {
         pp = fgets_trim(buff,100,fid,1);
         if (! pp) break;
         if (*pp <= ' ') continue;
         itemlist[jj++] = zstrdup(pp);                                           //  bugfix                             18.07.2
      }
      
      itemlist[jj] = 0;                                                          //  mark EOL
      fclose(fid);
   }

   select_meta_keys(itemlist,1);                                                 //  user edit of extras list           18.01
   
   fid = fopen(filex,"w");                                                       //  update extras list file            18.01
   if (! fid) {
      zmessageACK(Mwin,"%s \n %s",filex,strerror(errno));
      return 1;
   }
   
   for (ii = 0; ii < Mxmeta; ii++)
   {
      if (! itemlist[ii]) break;
      fprintf(fid,"%s\n",itemlist[ii]);
   }

   fclose(fid);

   return 1;
}


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

//  edit metadata menu function

void m_meta_edit_main(GtkWidget *, cchar *menu)
{
   void  edit_imagetags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  edit_recentags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  edit_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  edit_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   editmeta_dialog_event(zdialog *zd, cchar *event);

   cchar    *mapquest = "Geocoding by MapQuest";

   GtkWidget   *widget;
   zdialog     *zd;
   char        *ppv, pdate[12], ptime[12];
   char        cctext[exif_maxcc+50];
   char        RN[4] = "R0";
   int         ii;

   F1_help_topic = "edit_metadata";

   if (clicked_file) {                                                           //  use clicked file if present
      if (! curr_file || ! strmatch(clicked_file,curr_file))                     //  avoid f_open() re-entry            18.01
         f_open(clicked_file,0,0,1,0);
      clicked_file = 0;
   }
   
   if (! curr_file) {
      if (zdeditmeta) zdialog_free(zdeditmeta);
      zdeditmeta = 0;
      zd_mapgeotags = 0;
      return;
   }

   if (! init_geolocs()) return;                                                 //  initialize geotags

   if (FGWM == 'G') gallery(0,"paint",-1);                                       //  if gallery view, repaint

/***
          ___________________________________________________________
         |                      Edit Metadata                        |
         |                                                           |
         |  File: filename.jpg                                       |
         |  Image Date: [__________]  Time: [________]  [prev]       |
         |  Rating (stars): (o) 1  (o) 2  (o) 3  (o) 4  (o) 5  (o) 6 |
         |  Caption [______________________________________________] |
         |  Comments [_____________________________________________] |
         |  - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  location [_______________]  country [______________]     |
         |  latitude [__________]  longitude [__________]            |
         |  [Find] [Web] [Prev] [Clear]   Geocoding by MapQuest      |
         |  - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  Current Tags [_________________________________________] |
         |  Recent Tags [__________________________________________] |
         |  Enter New Tag [__________]  [Add]                        |
         |  Matching Tags [________________________________________] |
         |  - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  Defined Tags Category [______________________________|v] |
         |  |                                                      | |
         |  |                                                      | |
         |  |                                                      | |
         |  |                                                      | |
         |  |                                                      | |
         |  |                                                      | |
         |  |                                                      | |
         |  |______________________________________________________| |
         |                                                           |
         |                    [Manage Tags] [Prev] [Apply] [Cancel]  |
         |___________________________________________________________|

***/

   if (! zdeditmeta)                                                             //  (re) start edit dialog
   {
      zd = zdialog_new(E2X("Edit Metadata"),Mwin,Bmanagetags,Bprev,Bapply,Bcancel,null);
      zdeditmeta = zd;
      
      zdialog_add_ttip(zd,Bapply,E2X("save metadata to file"));

      //  File: xxxxxxxxx.jpg
      zdialog_add_widget(zd,"hbox","hbf","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","labf","hbf",E2X("File:"),"space=3");
      zdialog_add_widget(zd,"label","file","hbf","filename.jpg","space=5");

      //  Image Date [__________]  Time [_____]   [prev]
      zdialog_add_widget(zd,"hbox","hbdt","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labdate","hbdt",E2X("Image Date"),"space=3");
      zdialog_add_widget(zd,"zentry","date","hbdt",0,"size=12");
      zdialog_add_widget(zd,"label","space","hbdt",0,"space=5");
      zdialog_add_widget(zd,"label","labtime","hbdt",E2X("Time"),"space=3");
      zdialog_add_widget(zd,"zentry","time","hbdt",0,"size=8");
      zdialog_add_widget(zd,"button","ppdate","hbdt",Bprev,"space=8");
      zdialog_add_ttip(zd,"date","yyyy-mm-dd");
      zdialog_add_ttip(zd,"time","hh:mm[:ss]");

      //  Rating (stars): ʘ 1  ʘ 2  ʘ 3  ʘ 4  ʘ 5  ʘ 6
      zdialog_add_widget(zd,"hbox","hbrate","dialog");
      zdialog_add_widget(zd,"label","labrate","hbrate",E2X("Rating (stars):"),"space=3");
      zdialog_add_widget(zd,"radio","R0","hbrate","0","space=6");
      zdialog_add_widget(zd,"radio","R1","hbrate","1","space=6");
      zdialog_add_widget(zd,"radio","R2","hbrate","2","space=6");
      zdialog_add_widget(zd,"radio","R3","hbrate","3","space=6");
      zdialog_add_widget(zd,"radio","R4","hbrate","4","space=6");
      zdialog_add_widget(zd,"radio","R5","hbrate","5","space=6");

      zdialog_add_widget(zd,"hbox","space","dialog",0,"space=3");

      //  Caption [___________________________________________]
      zdialog_add_widget(zd,"hbox","hbcap","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labcap","hbcap",E2X("Caption"),"space=3");
      zdialog_add_widget(zd,"edit","caption","hbcap",0,"wrap|expand");

      //  Comments [__________________________________________]
      zdialog_add_widget(zd,"hbox","hbcom","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labcom","hbcom",E2X("Comments"),"space=3");
      zdialog_add_widget(zd,"edit","comments","hbcom",0,"wrap|expand");

      zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

      //  location [_____________]  country [____________]
      zdialog_add_widget(zd,"hbox","hbcc","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","labloc","hbcc",E2X("Location"),"space=5");
      zdialog_add_widget(zd,"zentry","location","hbcc",0,"expand");
      zdialog_add_widget(zd,"label","space","hbcc",0,"space=5");
      zdialog_add_widget(zd,"label","labcountry","hbcc",E2X("Country"),"space=5");
      zdialog_add_widget(zd,"zentry","country","hbcc",0,"expand");

      //  latitude [__________]  longitude [__________]     
      zdialog_add_widget(zd,"hbox","hbll","dialog");
      zdialog_add_widget(zd,"label","lablat","hbll","Latitude","space=3");
      zdialog_add_widget(zd,"zentry","lati","hbll",0,"size=10");
      zdialog_add_widget(zd,"label","space","hbll",0,"space=5");
      zdialog_add_widget(zd,"label","lablong","hbll","Longitude","space=3");
      zdialog_add_widget(zd,"zentry","longi","hbll",0,"size=10");

      //  [Find] [Web] [Prev] [Clear]   Geocoding by MapQuest
      zdialog_add_widget(zd,"hbox","hbgeo","dialog",0,"space=3");
      zdialog_add_widget(zd,"button","geofind","hbgeo",Bfind,"space=5");
      zdialog_add_widget(zd,"button","geoweb","hbgeo",Bweb,"space=5");
      zdialog_add_widget(zd,"button","geoprev","hbgeo",Bprev,"space=5");
      zdialog_add_widget(zd,"button","geoclear","hbgeo",Bclear,"space=5");
      zdialog_add_widget(zd,"label","labmq","hbgeo",mapquest,"space=3");

      zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

      //  Image Tags [________________________________________] 
      zdialog_add_widget(zd,"hbox","hbit","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labit","hbit",E2X("Image Tags"),"space=3");
      zdialog_add_widget(zd,"frame","frit","hbit",0,"expand");
      zdialog_add_widget(zd,"text","imagetags","frit",0,"wrap");

      //  Recent Tags [_______________________________________]
      zdialog_add_widget(zd,"hbox","hbrt","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labrt","hbrt",E2X("Recent Tags"),"space=3");
      zdialog_add_widget(zd,"frame","frrt","hbrt",0,"expand");
      zdialog_add_widget(zd,"text","recentags","frrt",0,"wrap");
      
      //  Enter New Tag [________________]  [Add]
      zdialog_add_widget(zd,"hbox","hbnt","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labnt","hbnt",E2X("Enter New Tag"),"space=3");
      zdialog_add_widget(zd,"zentry","newtag","hbnt",0,"size=20");
      zdialog_add_widget(zd,"zbutton","add","hbnt",Badd,"space=5");

      //  Matching Tags [_____________________________________]
      zdialog_add_widget(zd,"hbox","hbmt","dialog",0,"space=1");
      zdialog_add_widget(zd,"label","labmt","hbmt",E2X("Matching Tags"),"space=3");
      zdialog_add_widget(zd,"frame","frmt","hbmt",0,"expand");
      zdialog_add_widget(zd,"text","matchtags","frmt",0,"wrap");

      zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

      //  Defined Tags Category 
      zdialog_add_widget(zd,"hbox","hbdt1","dialog");
      zdialog_add_widget(zd,"label","labdt","hbdt1",E2X("Defined Tags Category"),"space=3");
      zdialog_add_widget(zd,"label","space","hbdt1",0,"expand");
      zdialog_add_widget(zd,"combo","defcats","hbdt1",0,"expand|space=5");

      zdialog_add_widget(zd,"hbox","hbdt2","dialog",0,"expand");
      zdialog_add_widget(zd,"scrwin","swdt2","hbdt2",0,"expand");
      zdialog_add_widget(zd,"text","deftags","swdt2",0,"wrap");
      
      zdialog_add_ttip(zd,"geofind",E2X("search known locations"));
      zdialog_add_ttip(zd,"geoweb",E2X("search using web service"));
      zdialog_add_ttip(zd,Bmanagetags,E2X("create tag categories and tags"));

      load_deftags();                                                            //  stuff defined tags into dialog
      deftags_stuff(zd,"ALL");
      defcats_stuff(zd);                                                         //  and defined categories

      widget = zdialog_widget(zd,"imagetags");                                   //  tag widget mouse functions
      textwidget_set_callbackfunc(widget,edit_imagetags_clickfunc);

      widget = zdialog_widget(zd,"recentags");
      textwidget_set_callbackfunc(widget,edit_recentags_clickfunc);

      widget = zdialog_widget(zd,"matchtags");
      textwidget_set_callbackfunc(widget,edit_matchtags_clickfunc);

      widget = zdialog_widget(zd,"deftags");
      textwidget_set_callbackfunc(widget,edit_deftags_clickfunc);

      zdialog_resize(zd,400,700);                                                //  run dialog
      zdialog_run(zd,editmeta_dialog_event,"parent");
   }

   zd = zdeditmeta;                                                              //  edit metadata active
   zd_mapgeotags = zd;                                                           //  map clicks active

   ppv = (char *) strrchr(curr_file,'/');
   zdialog_stuff(zd,"file",ppv+1);                                               //  stuff dialog fields from curr. file

   metadate_pdate(meta_pdate,pdate,ptime);                                       //  "yyyymmddhhmmss" to 
   zdialog_stuff(zd,"date",pdate);                                               //    "yyyy-mm-dd" and "hh:mm:ss"
   zdialog_stuff(zd,"time",ptime);

   for (ii = 0; ii <= 5; ii++) {                                                 //  set all rating radio buttons OFF
      RN[1] = '0' + ii;
      zdialog_stuff(zd,RN,0);
   }
   RN[1] = meta_rating[0];                                                       //  set radio button ON for current rating
   zdialog_stuff(zd,RN,1);

   repl_1str(meta_caption,cctext,"\\n","\n");
   zdialog_stuff(zd,"caption",cctext);
   repl_1str(meta_comments,cctext,"\\n","\n");
   zdialog_stuff(zd,"comments",cctext);

   if (strmatch(meta_location,"null")) zdialog_stuff(zd,"location","");          //  geotags data
   else zdialog_stuff(zd,"location",meta_location);                              //  if null, stuff blank
   if (strmatch(meta_country,"null")) zdialog_stuff(zd,"country","");
   else zdialog_stuff(zd,"country",meta_country);
   if (strmatch(meta_lati,"null")) zdialog_stuff(zd,"lati","");
   else zdialog_stuff(zd,"lati",meta_lati);
   if (strmatch(meta_longi,"null")) zdialog_stuff(zd,"longi","");
   else zdialog_stuff(zd,"longi",meta_longi);

   zdialog_stuff(zd,"imagetags",meta_tags);
   zdialog_stuff(zd,"recentags",tags_recentags);

   return;
}


//  mouse click functions for various text widgets for tags

void edit_imagetags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)   //  existing image tag was clicked
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return; 

   del_tag(txtag,meta_tags);                                                     //  remove tag from image
   zdialog_stuff(zdeditmeta,"imagetags",meta_tags);
   Fmetamod++;                                                                   //  note change

   zfree(txtag);
   return;
}


void edit_recentags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)   //  recent tag was clicked
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   add_tag(txtag,meta_tags,tagFcc);                                              //  add recent tag to image
   zdialog_stuff(zdeditmeta,"imagetags",meta_tags);
   Fmetamod++;                                                                   //  note change 

   zfree(txtag);
   return;
}


void edit_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)   //  matching tag was clicked
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   add_tag(txtag,meta_tags,tagFcc);                                              //  add matching tag to image
   Fmetamod++;                                                                   //  note change
   add_recentag(txtag);                                                          //  and add to recent tags

   zdialog_stuff(zdeditmeta,"imagetags",meta_tags);                              //  update dialog widgets
   zdialog_stuff(zdeditmeta,"recentags",tags_recentags);
   zdialog_stuff(zdeditmeta,"newtag","");
   zdialog_stuff(zdeditmeta,"matchtags","");

   zdialog_goto(zdeditmeta,"newtag");                                            //  put focus back on newtag widget

   zfree(txtag);
   return;
}


void edit_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)     //  defined tag was clicked
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;:",end);
   if (! txtag || end == ':') return;                                            //  tag category clicked, ignore

   add_tag(txtag,meta_tags,tagFcc);                                              //  add new tag to image
   zdialog_stuff(zdeditmeta,"imagetags",meta_tags);                              //    from defined tags list
   Fmetamod++;                                                                   //  note change

   add_recentag(txtag);                                                          //  and add to recent tags
   zdialog_stuff(zdeditmeta,"recentags",tags_recentags);

   zfree(txtag);
   return;
}


//  dialog event and completion callback function

int editmeta_dialog_event(zdialog *zd, cchar *event)                             //  overhauled
{
   char     pdate[12], ptime[12];                                                //  yyyy-mm-dd  and  hh:mm:ss
   char     *metadate, *metatime;                                                //  yyyymmdd  and  hhmmss
   cchar    *errmess;
   int      ii, jj, nt, cc1, cc2, ff, err;
   char     *pp1, *pp2;
   char     catgname[tagcc];
   char     newtag[tagcc], matchtags[20][tagcc];
   char     matchtagstext[(tagcc+2)*20];
   char     cctext[exif_maxcc+50];
   char     RN[4] = "R0";
   char     location[100], country[100], lati[20], longi[20];
   float    flati, flongi;
   
   if (! curr_file) zd->zstat = 4;                                               //  current file gone
   
   if (strmatch(event,"cancel")) zd->zstat = 4;

   if (strstr("date time caption comments",event))                               //  note change but process later
      Fmetamod++;

   if (strmatch(event,"ppdate")) {                                               //  repeat last date used
      if (*p_meta_pdate) {
         metadate_pdate(p_meta_pdate,pdate,ptime);
         zdialog_stuff(zd,"date",pdate);
         zdialog_stuff(zd,"time",ptime);
         Fmetamod++;
         return 1;
      }
   }

   if (strstr("R0 R1 R2 R3 R4 R5",event)) {                                      //  note if rating changed
      Fmetamod++;
      return 1;
   }

   if (strstr("location country lati longi",event)) {                            //  dialog inputs changed
      Fmetamod++;
      return 1;
   }

   if (strmatch(event,"geomap")) {                                               //  have geotags data from map click
      Fmetamod++;
      return 1;
   }
   
   if (strmatch(event,"geofind"))                                                //  [find] search location data
   {
      find_location(zd);                                                         //  find location data via user
      Fmetamod++;
      return 1;
   }

   if (strmatch(event,"geoweb"))                                                 //  [web] search location data
   {
      errmess = web_geocode(zd);                                                 //  look-up in web service
      if (errmess) zmessageACK(Mwin,errmess);                                    //  fail
      else Fmetamod++;
      return 1;
   }

   if (strmatch(event,"geoprev"))                                                //  [prev] stuff previous geotags
   {
      zdialog_stuff(zd,"location",p_meta_location);                              //  get last-used geotags
      zdialog_stuff(zd,"country",p_meta_country);
      zdialog_stuff(zd,"lati",p_meta_lati);
      zdialog_stuff(zd,"longi",p_meta_longi);
      Fmetamod++;
   }

   if (strmatch(event,"geoclear"))                                               //  [clear] location data
   {
      zdialog_stuff(zd,"location","");                                           //  erase dialog fields
      zdialog_stuff(zd,"country","");
      zdialog_stuff(zd,"lati","");
      zdialog_stuff(zd,"longi","");
      Fmetamod++;
      return 1;
   }

   if (strmatch(event,"defcats")) {                                              //  new tag category selection
      zdialog_fetch(zd,"defcats",catgname,tagcc);
      deftags_stuff(zd,catgname);
   }

   if (strmatch(event,"newtag"))                                                 //  new tag is being typed in
   {
      zdialog_stuff(zd,"matchtags","");                                          //  clear matchtags in dialog

      zdialog_fetch(zd,"newtag",newtag,tagcc);                                   //  get chars. typed so far
      cc1 = strlen(newtag);
      
      for (ii = jj = 0; ii <= cc1; ii++) {                                       //  remove foul characters
         if (strchr(",:;",newtag[ii])) continue;
         newtag[jj++] = newtag[ii];
      }
      
      if (jj < cc1) {                                                            //  something was removed
         newtag[jj] = 0;
         cc1 = jj;
         zdialog_stuff(zd,"newtag",newtag);
      }

      if (cc1 < 2) return 1;                                                     //  wait for at least 2 chars.

      for (ii = nt = 0; ii < maxtagcats; ii++)                                   //  loop all categories
      {
         pp2 = tags_deftags[ii];                                                 //  category: aaaaaa, bbbbb, ... tagN,
         if (! pp2) continue;                                                    //            |     |
         pp2 = strchr(pp2,':');                                                  //            pp1   pp2
         
         while (true)                                                            //  loop all deftags in category
         {
            pp1 = pp2 + 2;
            if (! *pp1) break;
            pp2 = strchr(pp1,',');
            if (! pp2) break;
            if (strmatchcaseN(newtag,pp1,cc1)) {                                 //  deftag matches chars. typed so far
               cc2 = pp2 - pp1;
               strncpy(matchtags[nt],pp1,cc2);                                   //  save deftags that match
               matchtags[nt][cc2] = 0;
               if (++nt == 20) return 1;                                         //  quit if 20 matches or more
            }
         }
      }
      
      if (nt == 0) return 1;                                                     //  no matches

      pp1 = matchtagstext;

      for (ii = 0; ii < nt; ii++)                                                //  matchtag list: aaaaa, bbb, cccc ...
      {
         strcpy(pp1,matchtags[ii]);
         pp1 += strlen(pp1);
         strcpy(pp1,", ");
         pp1 += 2;
      }
      
      zdialog_stuff(zd,"matchtags",matchtagstext);                               //  stuff matchtags in dialog
      return 1;
   }

   if (strmatch(event,"add"))                                                    //  enter new tag finished
   {
      zdialog_fetch(zd,"newtag",newtag,tagcc);                                   //  get finished tag
      cc1 = strlen(newtag);
      if (! cc1) return 1;
      if (newtag[cc1-1] == '\n') {                                               //  remove newline character
         cc1--;
         newtag[cc1] = 0;
      }

      for (ii = ff = 0; ii < maxtagcats; ii++)                                   //  loop all categories
      {
         pp2 = tags_deftags[ii];                                                 //  category: aaaaaa, bbbbb, ... tagN,
         if (! pp2) continue;                                                    //            |     |
         pp2 = strchr(pp2,':');                                                  //            pp1   pp2
         
         while (true)                                                            //  loop all deftags in category
         {
            pp1 = pp2 + 2;
            if (! *pp1) break;
            pp2 = strchr(pp1,',');
            if (! pp2) break;
            cc2 = pp2 - pp1;
            if (cc2 != cc1) continue;
            if (strmatchcaseN(newtag,pp1,cc1)) {                                 //  entered tag matches deftag
               strncpy(newtag,pp1,cc1);                                          //  use deftag upper/lower case
               ff = 1;
               break;
            }
         }

         if (ff) break;
      }

      add_tag(newtag,meta_tags,tagFcc);                                          //  add to image tag list
      Fmetamod++;                                                                //  note change
      add_recentag(newtag);                                                      //  and add to recent tags

      if (! ff) {                                                                //  if new tag, add to defined tags
         add_deftag((char *) "nocatg",newtag);
         deftags_stuff(zd,"ALL");
      }

      zdialog_stuff(zd,"newtag","");                                             //  update dialog widgets
      zdialog_stuff(zd,"imagetags",meta_tags);
      zdialog_stuff(zd,"recentags",tags_recentags);
      zdialog_stuff(zd,"matchtags","");

      zdialog_goto(zd,"newtag");                                                 //  put focus back on newtag widget
      return 1;
   }
   
   if (! zd->zstat) return 1;                                                    //  wait for completion

   if (zd->zstat == 1) {                                                         //  [manage tags]
      zd->zstat = 0;                                                             //  keep dialog active
      zdialog_show(zd,0);                                                        //  hide parent dialog
      manage_tags();
      return 1;
   }

   if (zd->zstat == 2)                                                           //  [prev] stuff previous file data
   {
      zd->zstat = 0;                                                             //  keep dialog active

      if (! *meta_pdate && *p_meta_pdate) {                                      //  stuff photo date only if none
         metadate_pdate(p_meta_pdate,pdate,ptime);
         zdialog_stuff(zd,"date",pdate);
         zdialog_stuff(zd,"time",ptime);
      }

      for (ii = 0; ii <= 5; ii++) {                                              //  stuff rating
         RN[1] = '0' + ii;                                                       //  radio buttons, "R0" to "R5"
         if (RN[1] == *p_meta_rating) zdialog_stuff(zd,RN,1);                    //  for ratings "0" to "5"
         else zdialog_stuff(zd,RN,0);
      }

      zdialog_stuff(zd,"location",p_meta_location);                              //  get last-used geotags
      zdialog_stuff(zd,"country",p_meta_country);
      zdialog_stuff(zd,"lati",p_meta_lati);
      zdialog_stuff(zd,"longi",p_meta_longi);

      zdialog_stuff(zd,"imagetags",p_meta_tags);                                 //  stuff tags
      strncpy0(meta_tags,p_meta_tags,tagFcc);

      repl_1str(p_meta_caption,cctext,"\\n","\n");                               //  stuff caption
      zdialog_stuff(zd,"caption",cctext);

      repl_1str(p_meta_comments,cctext,"\\n","\n");                              //  stuff comments
      zdialog_stuff(zd,"comments",cctext);
      
      Fmetamod++;
      return 1;
   }

   if (zd->zstat != 3) {                                                         //  [cancel] or [x]
      zdialog_free(zd);                                                          //  kill dialog
      zdeditmeta = 0;
      zd_mapgeotags = 0;                                                         //  deactivate map clicks
      Fmetamod = 0;
      return 1;
   }

   zd->zstat = 0;                                                                //  [apply] - keep dialog active
   
   gtk_window_present(MWIN);                                                     //  return focus to main window

   if (! Fmetamod) return 1;                                                     //  no metadata changes

   zdialog_fetch(zd,"date",pdate,12);                                            //  get photo date and time
   zdialog_fetch(zd,"time",ptime,12);
   if (*pdate) {                                                                 //  date available
      metadate = pdate_metadate(pdate);                                          //  validate
      if (! metadate) return 1;                                                  //  bad, re-input
      strcpy(meta_pdate,metadate);                                               //  convert to yyyymmdd
      if (*ptime) {                                                              //  time available
         metatime = ptime_metatime(ptime);                                       //  validate
         if (! metatime) return 1;                                               //  bad, re-input
         strcat(meta_pdate,metatime);                                            //  append hhmmss
      }
   }
   else *meta_pdate = 0;                                                         //  leave empty

   strcpy(meta_rating,"0");
   for (ii = 0; ii <= 5; ii++) {                                                 //  get which rating radio button ON
      RN[1] = '0' + ii;
      zdialog_fetch(zd,RN,jj);
      if (jj) meta_rating[0] = '0' + ii;                                         //  set corresponding rating
   }

   zdialog_fetch(zd,"caption",cctext,exif_maxcc);                                //  get new caption
   repl_1str(cctext,meta_caption,"\n","\\n");                                    //  replace newlines with "\n"
   zdialog_fetch(zd,"comments",cctext,exif_maxcc);                               //  get new comments
   repl_1str(cctext,meta_comments,"\n","\\n");                                   //  replace newlines with "\n"

   zdialog_fetch(zd,"location",location,100);                                    //  get location from dialog
   zdialog_fetch(zd,"country",country,100);
   *location = toupper(*location);                                               //  capitalize
   *country = toupper(*country);
   zdialog_stuff(zd,"location",location);
   zdialog_stuff(zd,"country",country);

   zdialog_fetch(zd,"lati",lati,20);                                             //  get latitude, longitude
   zdialog_fetch(zd,"longi",longi,20);
   
   if (*lati > ' ' && ! strmatch(lati,"null") &&                                 //  if coordinates present, validate
       *longi > ' ' && ! strmatch(longi,"null")) {
      err = validate_latlong(lati,longi,flati,flongi);
      if (err) {
         zmessageACK(Mwin,E2X("bad latitude/longitude: %s %s"),lati,longi);
         return 1;
      }
   }

   strncpy0(meta_location,location,100);                                         //  save geotags in image file EXIF
   strncpy0(meta_country,country,100);                                           //    and in search-index file
   strncpy0(meta_lati,lati,20);
   strncpy0(meta_longi,longi,20);

   put_geolocs(zd);                                                              //  update geolocs table in memory
   save_filemeta(curr_file);                                                     //  save metadata changes to image file

   return 1;
}


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

//  manage tags function - auxilliary dialog

zdialog  *zdmanagetags = 0;

void manage_tags()
{
   void  manage_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   managetags_dialog_event(zdialog *zd, cchar *event);

   GtkWidget   *widget;
   zdialog     *zd;

/***
          ______________________________________________________________
         |       Manage Tags                                            |
         |                                                              |
         | category [____________]  tag [___________] [Create] [Delete] |
         |                                                              |
         | Defined Tags: _____________________________________________  |
         | |                                                          | |
         | | category1: tag11, tag12, tag13 ...                       | |
         | | category2: tag21, tag22, tag23 ...                       | |
         | |  ...                                                     | |
         | |                                                          | |
         | |                                                          | |
         | |                                                          | |
         | |                                                          | |
         | |                                                          | |
         | |__________________________________________________________| |
         |                                                              |
         |                                         [orphan tags] [Done] |
         |______________________________________________________________|

***/

   if (zdmanagetags) return;
   zd = zdialog_new(E2X("Manage Tags"),Mwin,E2X("orphan tags"),Bdone,null);
   zdmanagetags = zd;

   zdialog_add_widget(zd,"hbox","hb7","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labcatg","hb7",E2X("category"),"space=5");
   zdialog_add_widget(zd,"zentry","catg","hb7",0,"size=12");
   zdialog_add_widget(zd,"label","space","hb7",0,"space=5");
   zdialog_add_widget(zd,"label","labtag","hb7",E2X("tag"),"space=5");
   zdialog_add_widget(zd,"zentry","tag","hb7",0,"size=20|expand");
   zdialog_add_widget(zd,"label","space","hb7",0,"space=5");
   zdialog_add_widget(zd,"button","create","hb7",Bcreate);
   zdialog_add_widget(zd,"button","delete","hb7",Bdelete);

   zdialog_add_widget(zd,"hbox","hb8","dialog");
   zdialog_add_widget(zd,"label","labdeftags","hb8",E2X("Defined Tags:"),"space=5");
   zdialog_add_widget(zd,"hbox","hb9","dialog",0,"expand");
   zdialog_add_widget(zd,"frame","frame8","hb9",0,"space=5|expand");
   zdialog_add_widget(zd,"scrwin","scrwin8","frame8",0,"expand");
   zdialog_add_widget(zd,"text","deftags","scrwin8",0,"expand|wrap");

   widget = zdialog_widget(zd,"deftags");                                        //  tag widget mouse function
   textwidget_set_callbackfunc(widget,manage_deftags_clickfunc);

   load_deftags();                                                               //  stuff defined tags into dialog
   deftags_stuff(zd,"ALL");

   zdialog_resize(zd,0,400);
///zdialog_set_modal(zd);                                                        //  blocks cancel orphan tags report   17.08.3
   zdialog_run(zd,managetags_dialog_event,"parent");                             //  run dialog
   zdialog_wait(zd);
   zdialog_free(zd); 

   return;
}


//  mouse click functions for widget having tags

void manage_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)   //  tag or tag category was clicked
{
   char     *txword, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txword = textwidget_word(widget,line,pos,",;:",end);
   if (! txword) return;
   
   if (end == ':') zdialog_stuff(zdmanagetags,"catg",txword);                    //  selected category >> dialog widget
   else zdialog_stuff(zdmanagetags,"tag",txword);                                //  selected tag >> dialog widget

   zfree(txword);
   return;
}


//  dialog event and completion callback function

int managetags_dialog_event(zdialog *zd, cchar *event)
{
   void tag_orphans(GtkWidget *);

   char        tag[tagcc], catg[tagcc];
   int         err, changed = 0;

   if (zd->zstat)
   {
      if (zd->zstat == 1) {                                                      //  report orphan tags
         zd->zstat = 0;                                                          //  keep dialog active
         tag_orphans(zdialog_widget(zd,"dialog"));
      }

      else {                                                                     //  done or [x]
         zdialog_free(zd);
         if (zdeditmeta) zdialog_show(zdeditmeta,1);                             //  reinstate parent dialog
         zdmanagetags = 0;
         return 0;
      }
   }

   if (strmatch(event,"create")) {                                               //  add new tag to defined tags
      zdialog_fetch(zd,"catg",catg,tagcc);
      zdialog_fetch(zd,"tag",tag,tagcc);
      err = add_deftag(catg,tag);
      if (! err) changed++;
   }

   if (strmatch(event,"delete")) {                                               //  remove tag from defined tags
      zdialog_fetch(zd,"tag",tag,tagcc);
      del_deftag(tag);
      changed++;
   }

   if (changed) {
      save_deftags();                                                            //  save tag updates to file
      deftags_stuff(zd,"ALL");                                                   //  update dialog "deftags" window
      if (zdeditmeta)                                                            //  and edit metadata dialog if active
         deftags_stuff(zdeditmeta,"ALL");
      if (zdbatchtags)                                                           //  and batch tags dialog if active
         deftags_stuff(zdbatchtags,"ALL");
   }

   return 0;
}


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

//  edit EXIF/IPTC data - add or change specified EXIF/IPTC/etc. key

void m_meta_edit_any(GtkWidget *, cchar *menu)
{
   int   meta_edit_any_dialog_event(zdialog *zd, cchar *event);
   void  meta_edit_any_clickfunc(GtkWidget *, int line, int pos, int kbkey);

   zdialog     *zd;
   GtkWidget   *mtext;
   char        filename[200], buff[100];
   cchar       *pp1[1];
   char        *pp2[1], *pp;
   FILE        *fid;

   F1_help_topic = "edit_any_metadata";

   if (clicked_file) {                                                           //  use clicked file if present
      if (! curr_file || ! strmatch(clicked_file,curr_file))                     //  avoid f_open() re-entry            18.01
         f_open(clicked_file,0,0,1,0);
      clicked_file = 0;
   }

   if (! curr_file) {
      if (zdeditanymeta) zdialog_free(zdeditanymeta);
      zdeditanymeta = 0;
      return;
   }
   
   if (FGWM == 'G') gallery(0,"paint",-1);                                       //  if gallery view, repaint

/***
       _____________________________________________________
      |  Click to Select   | File: filename.jpg             |
      |                    |                                |
      |  (metadata list)   | key name [___________] [fetch] |
      |                    | key value [__________________] |
      |                    |                                |
      |                    |                                |
      |                    |                                |
      |                    |      [Full List] [Save] [Done] |
      |____________________|________________________________|

***/

   if (! zdeditanymeta)                                                          //  popup dialog if not already
   {
      zd = zdialog_new(E2X("Edit Any Metadata"),Mwin,E2X("Full List"),Bsave,Bdone,null);
      zdeditanymeta = zd;
      zdialog_add_widget(zd,"hbox","hb1","dialog",0,"expand");
      zdialog_add_widget(zd,"vbox","vb1","hb1",0,"expand|space=3");
      zdialog_add_widget(zd,"label","lab1","vb1",E2X("click to select"),"size=25");
      zdialog_add_widget(zd,"frame","frb1","vb1",0,"expand");
      zdialog_add_widget(zd,"scrwin","scrb1","frb1",0,"expand");
      zdialog_add_widget(zd,"text","mtext","scrb1",0,"expand");
      zdialog_add_widget(zd,"vbox","vb2","hb1",0,"expand|space=3");
      zdialog_add_widget(zd,"hbox","hbf","vb2",0,"space=6");
      zdialog_add_widget(zd,"label","labf","hbf",E2X("File:"),"space=3");
      zdialog_add_widget(zd,"label","file","hbf","filename.jpg","space=5");
      zdialog_add_widget(zd,"hbox","hbkey","vb2",0,"space=2");
      zdialog_add_widget(zd,"hbox","hbdata","vb2",0,"space=2");
      zdialog_add_widget(zd,"label","labkey","hbkey",E2X("key name"));
      zdialog_add_widget(zd,"zentry","keyname","hbkey",0,"expand");
      zdialog_add_widget(zd,"button","fetch","hbkey",Bfetch,"space=5");
      zdialog_add_widget(zd,"label","labdata","hbdata",E2X("key value"));
      zdialog_add_widget(zd,"zentry","keydata","hbdata",0,"expand");

      zdialog_resize(zd,600,300);
      zdialog_run(zd,meta_edit_any_dialog_event,"parent");

      mtext = zdialog_widget(zd,"mtext");                                        //  make clickable metadata list
      textwidget_clear(mtext);

      snprintf(filename,200,"%s/metadata_short_list",get_zhomedir());
      fid = fopen(filename,"r");                                                 //  read metadata list
      if (! fid) {
         zmessageACK(Mwin,"%s \n %s",filename,strerror(errno));
         return;
      }

      while (true) {                                                             //  populate dialog, left side
         pp = fgets_trim(buff,100,fid,1);
         if (! pp) break;
         if (*pp <= ' ') continue;
         if (strstr(buff,"White Balance")) continue;
         textwidget_append(mtext,0,"%s \n",buff);
      }
      fclose(fid);

      textwidget_set_callbackfunc(mtext,meta_edit_any_clickfunc);                //  set click callback func
      
      *keyname = 0;
   }

   zd = zdeditanymeta;

   pp = strrchr(curr_file,'/');                                                  //  stuff file name in dialog
   if (pp) zdialog_stuff(zd,"file",pp+1);

   if (*keyname)                                                                 //  update live dialog
   {
      pp1[0] = keyname;                                                          //  look for key data
      exif_get(curr_file,pp1,pp2,1);
      if (pp2[0]) {
         strncpy0(keydata,pp2[0],exif_maxcc);
         zfree(pp2[0]);
      }
      else *keydata = 0;
      zdialog_stuff(zd,"keydata",keydata);                                       //  stuff into dialog
   }

   return;
}


//  dialog event and completion callback function

int meta_edit_any_dialog_event(zdialog *zd, cchar *event)
{
   cchar    *pp1[1];
   char     *pp2[1];
   int      err;
   
   if (! curr_file) return 1;

   if (strmatch(event,"fetch"))                                                  //  accept entered key name            17.08
   {
      zd->zstat = 0;                                                             //  keep dialog active

      zdialog_fetch(zd,"keyname",keyname,40);                                    //  get key name from dialog
      strCompress(keyname);
      pp1[0] = keyname;                                                          //  look for key data
      exif_get(curr_file,pp1,pp2,1);
      if (pp2[0]) {
         strncpy0(keydata,pp2[0],exif_maxcc);
         zfree(pp2[0]);
      }
      else *keydata = 0;
      zdialog_stuff(zd,"keydata",keydata);                                       //  stuff into dialog
   }

   if (! zd->zstat) return 1;                                                    //  wait for completion

   if (zd->zstat == 1) {                                                         //  show full list
      zd->zstat = 0;                                                             //  keep dialog active
      zmessageACK(Mwin,E2X("The command: $ man Image::ExifTool::TagNames \n"
                           "will show over 15000 \"standard\" tag names"));
   }

   else if (zd->zstat == 2)                                                      //  save
   {
      zd->zstat = 0;                                                             //  keep dialog active
      zdialog_fetch(zd,"keyname",keyname,40);                                    //  get key name from dialog
      zdialog_fetch(zd,"keydata",keydata,exif_maxcc); 
      strCompress(keyname);
      pp1[0] = keyname;
      pp2[0] = keydata;
      err = exif_put(curr_file,pp1,(cchar **) pp2,1);                            //  change metadata in image file
      if (err) zmessageACK(Mwin,"error: %s",strerror(err));
      load_filemeta(curr_file);                                                  //  update image index in case 
      update_image_index(curr_file);                                             //    searchable metadata item updated
      if (zdexifview) meta_view(0);                                              //  update exif view if active
   }

   else {
      zdialog_free(zd);                                                          //  done or cancel
      zdeditanymeta = 0;
   }

   return 1;
}


//  get clicked tag name from short list and insert into dialog

void meta_edit_any_clickfunc(GtkWidget *widget, int line, int pos, int kbkey) 
{
   char        *pp, *pp2[1];
   cchar       *pp1[1];
   
   if (! zdeditanymeta) return;
   if (! curr_file) return;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   pp = textwidget_line(widget,line,1);                                          //  get clicked line, highlight
   if (! pp || ! *pp) return;
   textwidget_highlight_line(widget,line);

   zdialog_stuff(zdeditanymeta,"keyname",pp);

   zdialog_fetch(zdeditanymeta,"keyname",keyname,40);                            //  get key name from dialog
   strCompress(keyname);

   pp1[0] = keyname;                                                             //  look for key data
   exif_get(curr_file,pp1,pp2,1);
   if (pp2[0]) {
      strncpy0(keydata,pp2[0],exif_maxcc);
      zfree(pp2[0]);
   }
   else *keydata = 0;
   zdialog_stuff(zdeditanymeta,"keydata",keydata);                               //  stuff into dialog

   return;
}


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

//  delete EXIF/IPTC data, specific key or all data

void m_meta_delete(GtkWidget *, cchar *menu)
{
   int   meta_delete_dialog_event(zdialog *zd, cchar *event);

   zdialog     *zd;
   char        *pp;

   F1_help_topic = "delete_metadata";

   if (clicked_file) {                                                           //  use clicked file if present
      if (! curr_file || ! strmatch(clicked_file,curr_file))                     //  avoid f_open() re-entry            18.01
         f_open(clicked_file,0,0,1,0);
      clicked_file = 0;
   }

   if (FGWM == 'G') gallery(0,"paint",-1);                                       //  if gallery view, repaint

/***
       _________________________________________
      |           Delete Metadata               |
      |                                         |
      | File: [______________________________]  |
      |                                         |
      | (o) ALL  (o) One Key: [______________]  |
      |                                         |
      |                       [apply] [cancel]  |
      |_________________________________________|
      
***/

   if (! zddeletemeta)
   {
      zd = zdialog_new(E2X("Delete Metadata"),Mwin,Bapply,Bcancel,null);
      zddeletemeta = zd;
      zdialog_add_widget(zd,"hbox","hbf","dialog");
      zdialog_add_widget(zd,"label","labf","hbf",E2X("File:"),"space=3");
      zdialog_add_widget(zd,"label","file","hbf",0,"space=5");
      zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
      zdialog_add_widget(zd,"radio","kall","hb1",E2X("All"),"space=5");
      zdialog_add_widget(zd,"radio","key1","hb1",E2X("One Key:"));
      zdialog_add_widget(zd,"zentry","keyname","hb1",0,"size=20");
      zdialog_stuff(zd,"key1",1);
      zdialog_run(zd,meta_delete_dialog_event,"parent");
   }

   zd = zddeletemeta;
   pp = (char *) "";
   if (curr_file) {
      pp = strrchr(curr_file,'/');
      if (pp) pp++;
      else pp = curr_file;
   }

   zdialog_stuff(zd,"file",pp);                                                  //  18.01
   return;
}


//  dialog event and completion callback function

int meta_delete_dialog_event(zdialog *zd, cchar *event)
{
   int         kall, key1;
   char        keyname[40];
   char        *file;

   if (! zd->zstat) return 1;                                                    //  wait for completion

   if (zd->zstat != 1) {                                                         //  canceled
      zdialog_free(zd);
      zddeletemeta = 0;
      return 1;
   }

   zd->zstat = 0;                                                                //  dialog remains active

   if (! curr_file) return 1;

   zdialog_fetch(zd,"kall",kall);
   zdialog_fetch(zd,"key1",key1);
   zdialog_fetch(zd,"keyname",keyname,40);
   strCompress(keyname);

   if (! kall && ! key1) return 1;

   file = zescape_quotes(curr_file);                                             //  18.07

   if (kall)                                                                     //  update file metadata
      shell_ack("exiftool -m -q -overwrite_original -all=  \"%s\"",file);
   else if (key1)
      shell_ack("exiftool -m -q -overwrite_original -%s=  \"%s\"",keyname,file);

   zfree(file);

   load_filemeta(curr_file);                                                     //  update image index in case a 
   update_image_index(curr_file);                                                //    searchable metadata deleted

   if (zdexifview) meta_view(0);                                                 //  update exif view if active
   return 1;
}


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

//  Show captions and comments on top of current image in main window.
//  Menu call (menu arg not null): toggle switch on/off.
//  Non-menu call: write caption/comment on image if switch is ON.

void m_meta_captions(GtkWidget *, cchar *menu)
{
   cchar        *keynames[2] = { iptc_caption_key, exif_comment_key };
   char         *pp, *keyvals[2];
   char         fname[200], caption[200], comment[200];
   static char  text[402];

   F1_help_topic = "show_captions";
   
   if (menu) {
      Fcaptions = 1 - Fcaptions;                                                 //  menu call, flip status             18.07
      if (! Fcaptions) {
         erase_toptext(1);
         Fpaintnow();
      }
   }

   if (! Fcaptions) return;
   if (! curr_file) return;
   
   pp = strrchr(curr_file,'/');
   if (pp) pp++;
   else pp = curr_file;
   strncpy0(fname,pp,200);
   
   *caption = *comment = 0;

   exif_get(curr_file,keynames,keyvals,2);                                       //  get captions and comments metadata

   if (keyvals[0]) {
      strncpy0(caption,keyvals[0],200);
      zfree(keyvals[0]);
   }

   if (keyvals[1]) {
      strncpy0(comment,keyvals[1],200);
      zfree(keyvals[1]);
   }

   strcpy(text,fname); 

   if (*caption) {
      strcat(text,"\n");
      strcat(text,caption);
   }

   if (*comment) {
      strcat(text,"\n");
      strcat(text,comment);
   }

   for (int ii = 0; text[ii]; ii++)                                              //  replace "\n" with newline chars.
      if (text[ii] == '\\' && text[ii+1] == 'n')
         memmove(text+ii,"\n ",2);

   if (*text) add_toptext(1,0,0,text,"Sans 10");
   Fpaintnow();

   return;
}


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

//  menu function - add and remove tags for many files at once

namespace batchtags
{
   char        addtags[tagMcc];                                                  //  tags to add, list
   char        deltags[tagMcc];                                                  //  tags to remove, list
   int         radadd, raddel;                                                   //  dialog radio buttons
   char        countmess[80];
}


void m_batch_tags(GtkWidget *, cchar *menu)                                      //  combine batch add/del tags
{
   using namespace batchtags;

   void  batch_addtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  batch_deltags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  batch_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  batch_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   batch_tags_dialog_event(zdialog *zd, cchar *event);

   char        *ptag, *file;
   int         zstat, ii, jj, err, yn;
   zdialog     *zd;
   GtkWidget   *widget;

   F1_help_topic = "batch_tags";

   if (checkpend("all")) return;                                                 //  check nothing pending
   Fblock = 1;

/***
          ________________________________________________________
         |           Batch Add/Remove Tags                        |
         |                                                        |
         |  [Select Files]  NN files selected                     |
         |                                                        |
         |  (o) tags to add    [________________________________] |
         |  (o) tags to remove [________________________________] |
         |  - - - - - - - - - - - - - - - - - - - - - - - - - - - |
         |  Enter New Tag [___________] [Add]                     |
         |  Matching Tags [_____________________________________] |
         |  - - - - - - - - - - - - - - - - - - - - - - - - - - - |
         |  Defined Tags Category [___________________________|v] |
         |  |                                                   | |
         |  |                                                   | |
         |  |                                                   | |
         |  |                                                   | |
         |  |                                                   | |
         |  |                                                   | |
         |  |___________________________________________________| |
         |                                                        |
         |                      [Manage Tags] [Proceed] [Cancel]  |
         |________________________________________________________|

***/

   zd = zdialog_new(E2X("Batch Add/Remove Tags"),Mwin,Bmanagetags,Bproceed,Bcancel,null);
   zdbatchtags = zd;

   //  [Select Files]  NN files selected
   zdialog_add_widget(zd,"hbox","hbfiles","dialog",0,"space=3");
   zdialog_add_widget(zd,"button","files","hbfiles",Bselectfiles,"space=5");
   zdialog_add_widget(zd,"label","labcount","hbfiles",Bnofileselected,"space=10");

   //  (o) tags to add    [_______________________________________]
   //  (o) tags to remove [_______________________________________]
   zdialog_add_widget(zd,"hbox","hbtags","dialog",0,"space=3");
   zdialog_add_widget(zd,"vbox","vb1","hbtags",0,"space=3|homog");
   zdialog_add_widget(zd,"vbox","vb2","hbtags",0,"space=3|homog|expand");
   zdialog_add_widget(zd,"radio","radadd","vb1",E2X("tags to add"));
   zdialog_add_widget(zd,"radio","raddel","vb1",E2X("tags to remove"));
   zdialog_add_widget(zd,"frame","fradd","vb2",0,"expand");
   zdialog_add_widget(zd,"text","addtags","fradd",0,"expand|wrap");
   zdialog_add_widget(zd,"frame","frdel","vb2",0,"expand");
   zdialog_add_widget(zd,"text","deltags","frdel",0,"expand|wrap");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

   //  Enter New Tag [________________]  [Add]
   zdialog_add_widget(zd,"hbox","hbnt","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labnt","hbnt",E2X("Enter New Tag"),"space=3");
   zdialog_add_widget(zd,"zentry","newtag","hbnt");
   zdialog_add_widget(zd,"button","add","hbnt",Badd,"space=5");

   //  Matching Tags [____________________________________________]
   zdialog_add_widget(zd,"hbox","hbmt","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labmt","hbmt",E2X("Matching Tags"),"space=3");
   zdialog_add_widget(zd,"frame","frmt","hbmt",0,"space=3|expand");
   zdialog_add_widget(zd,"text","matchtags","frmt",0,"wrap");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

   //  Defined Tags Category [__________________________________|v]
   zdialog_add_widget(zd,"hbox","space","dialog");
   zdialog_add_widget(zd,"hbox","hbdt1","dialog");
   zdialog_add_widget(zd,"label","labdt","hbdt1",E2X("Defined Tags Category"),"space=3");
   zdialog_add_widget(zd,"combo","defcats","hbdt1",0,"expand|space=5");
   zdialog_add_widget(zd,"hbox","hbdt2","dialog",0,"expand");
   zdialog_add_widget(zd,"frame","frdt2","hbdt2",0,"expand|space=3");
   zdialog_add_widget(zd,"scrwin","swdt2","frdt2",0,"expand");
   zdialog_add_widget(zd,"text","deftags","swdt2",0,"wrap");

   zdialog_add_ttip(zd,Bmanagetags,E2X("create tag categories and tags"));

   zdialog_stuff(zd,"radadd",1);                                                 //  initz. radio buttons
   zdialog_stuff(zd,"raddel",0);

   load_deftags();                                                               //  stuff defined tags into dialog
   deftags_stuff(zd,"ALL");
   defcats_stuff(zd);                                                            //  and defined categories

   *addtags = *deltags = 0;

   if (menu) gallery_select_clear();                                             //  clear gallery_select() file list
   else {
      snprintf(countmess,80,Bfileselected,GScount);                              //  re-run with same files
      zdialog_stuff(zd,"labcount",countmess);
   }

   widget = zdialog_widget(zd,"addtags");                                        //  tag widget mouse functions
   textwidget_set_callbackfunc(widget,batch_addtags_clickfunc);

   widget = zdialog_widget(zd,"deltags");
   textwidget_set_callbackfunc(widget,batch_deltags_clickfunc);

   widget = zdialog_widget(zd,"matchtags");
   textwidget_set_callbackfunc(widget,batch_matchtags_clickfunc);

   widget = zdialog_widget(zd,"deftags");
   textwidget_set_callbackfunc(widget,batch_deftags_clickfunc);

   zdialog_resize(zd,500,500);                                                   //  run dialog

   zdialog_run(zd,batch_tags_dialog_event,"parent");
   zstat = zdialog_wait(zd);                                                     //  wait for dialog completion
   zdialog_free(zd);

   zdbatchtags = 0;

   if (zstat != 2) {                                                             //  cancel
      Fblock = 0;
      return;
   }

   popup_report_open(Mwin,"Batch Tags",500,200);                                 //  status report popup window
   
   for (ii = 0; ii < GScount; ii++)                                              //  loop all selected files
   {
      zmainsleep(0.1);                                                           //  keep GTK alive

      file = GSfiles[ii];                                                        //  display image
      err = f_open(file,0,0,0);
      if (err) continue;

      popup_report_write(0,"%s \n",file);                                        //  report progress
      popup_report_bottom();                                                     //  18.07

      for (jj = 1; ; jj++)                                                       //  remove tags if present
      {
         ptag = (char *) strField(deltags,",;",jj);
         if (! ptag) break;
         if (*ptag == ' ') continue;
         err = del_tag(ptag,meta_tags);
         if (err) continue;
      }

      for (jj = 1; ; jj++)                                                       //  add new tags unless already
      {
         ptag = (char *) strField(addtags,",;",jj);
         if (! ptag) break;
         if (*ptag == ' ') continue;
         err = add_tag(ptag,meta_tags,tagFcc);
         if (err == 2) {
            zmessageACK(Mwin,E2X("%s \n too many tags"),file);
            break;
         }
      }

      save_filemeta(file);                                                       //  save tag changes
   }

   popup_report_write(0,"%s \n",Bcompleted);
   popup_report_bottom();                                                        //  18.07

   popup_report_move(-200,0);

   Fblock = 0;
   
   yn = zmessageYN(Mwin,E2X("repeat with same files?"));                         //  allow repeat with same files       18.01
   if (yn) {
      popup_report_close(0);
      m_batch_tags(0,0);
   }

   return;
}


//  mouse click functions for widgets holding tags

void batch_addtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)    //  a tag in the add list was clicked
{
   using namespace batchtags;

   char     *txtag, end;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   del_tag(txtag,addtags);                                                       //  remove tag from list
   zdialog_stuff(zdbatchtags,"addtags",addtags);
   
   zfree(txtag);
   return;
}


void batch_deltags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)    //  a tag in the remove list was clicked
{
   using namespace batchtags;

   char     *txtag, end;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   del_tag(txtag,deltags);                                                       //  remove tag from list
   zdialog_stuff(zdbatchtags,"deltags",deltags);

   zfree(txtag);
   return;
}


void batch_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)  //  matching tag was clicked
{
   using namespace batchtags;

   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   zdialog_fetch(zdbatchtags,"radadd",radadd);                                   //  which radio button?

   if (radadd) {
      add_tag(txtag,addtags,tagMcc);                                             //  add recent tag to tag add list
      zdialog_stuff(zdbatchtags,"addtags",addtags);
   }
   else {
      add_tag(txtag,deltags,tagMcc);                                             //  add recent tag to tag remove list
      zdialog_stuff(zdbatchtags,"deltags",deltags);
   }

   zdialog_stuff(zdbatchtags,"newtag","");                                       //  clear newtag and matchtags
   zdialog_stuff(zdbatchtags,"matchtags","");

   zdialog_goto(zdbatchtags,"newtag");                                           //  put focus back on newtag widget

   zfree(txtag);
   return;
}


void batch_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)    //  a defined tag was clicked
{
   using namespace batchtags;

   char     *txtag, end;
   int      radadd;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;:",end);
   if (! txtag || end == ':') return;                                            //  tag category clicked, ignore

   zdialog_fetch(zdbatchtags,"radadd",radadd);                                   //  which radio button?

   if (radadd) {
      add_tag(txtag,addtags,tagMcc);                                             //  add defined tag to tag add list
      zdialog_stuff(zdbatchtags,"addtags",addtags);
   }
   else {
      add_tag(txtag,deltags,tagMcc);                                             //  add defined tag to tag remove list
      zdialog_stuff(zdbatchtags,"deltags",deltags);
   }

   zfree(txtag);
   return;
}


//  batchTags dialog event function

int batch_tags_dialog_event(zdialog *zd, cchar *event)
{
   using namespace batchtags;

   char     catgname[tagcc];
   int      ii, jj, nt, cc1, cc2, ff;
   char     *pp1, *pp2;
   char     newtag[tagcc], matchtags[20][tagcc];
   char     matchtagstext[(tagcc+2)*20];

   if (strmatch(event,"cancel")) zd->zstat = 3;

   if (zd->zstat)                                                                //  dialog completed
   {
      if (zd->zstat == 1) {                                                      //  manage tags
         zd->zstat = 0;                                                          //  keep dialog active
         zdialog_show(zd,0);                                                     //  hide parent dialog
         manage_tags();
         zdialog_show(zd,1);
      }

      if (zd->zstat == 2) {                                                      //  proceed
         if (! GScount || (*addtags <= ' ' && *deltags <= ' ')) {
            zmessageACK(Mwin,E2X("specify files and tags"));
            zd->zstat = 0;                                                       //  keep dialog active
         }
      }

      return 1;                                                                  //  cancel
   }

   if (strmatch(event,"files"))                                                  //  select images to process
   {
      zdialog_show(zd,0);                                                        //  hide parent dialog
      gallery_select();                                                          //  get new list
      zdialog_show(zd,1);
      snprintf(countmess,80,Bfileselected,GScount);
      zdialog_stuff(zd,"labcount",countmess);
   }
   
   if (strstr("radadd raddel",event)) {                                          //  get state of radio buttons
      zdialog_fetch(zd,"radadd",radadd);
      zdialog_fetch(zd,"raddel",raddel);
   }

   if (strmatch(event,"defcats")) {                                              //  new tag category selection
      zdialog_fetch(zd,"defcats",catgname,tagcc);
      deftags_stuff(zd,catgname);
   }

   if (strmatch(event,"newtag"))                                                 //  new tag is being typed in
   {
      zdialog_stuff(zd,"matchtags","");                                          //  clear matchtags in dialog

      zdialog_fetch(zd,"newtag",newtag,tagcc);                                   //  get chars. typed so far
      cc1 = strlen(newtag);
      
      for (ii = jj = 0; ii <= cc1; ii++) {                                       //  remove foul characters
         if (strchr(",:;",newtag[ii])) continue;
         newtag[jj++] = newtag[ii];
      }
      
      if (jj < cc1) {                                                            //  something was removed
         newtag[jj] = 0;
         cc1 = jj;
         zdialog_stuff(zd,"newtag",newtag);
      }

      if (cc1 < 2) return 1;                                                     //  wait for at least 2 chars.

      for (ii = nt = 0; ii < maxtagcats; ii++)                                   //  loop all categories
      {
         pp2 = tags_deftags[ii];                                                 //  category: aaaaaa, bbbbb, ... tagN,
         if (! pp2) continue;                                                    //            |     |
         pp2 = strchr(pp2,':');                                                  //            pp1   pp2
         
         while (true)                                                            //  loop all deftags in category
         {
            pp1 = pp2 + 2;
            if (! *pp1) break;
            pp2 = strchr(pp1,',');
            if (! pp2) break;
            if (strmatchcaseN(newtag,pp1,cc1)) {                                 //  deftag matches chars. typed so far
               cc2 = pp2 - pp1;
               strncpy(matchtags[nt],pp1,cc2);                                   //  save deftags that match
               matchtags[nt][cc2] = 0;
               if (++nt == 20) return 1;                                         //  quit if 20 matches or more
            }
         }
      }
      
      if (nt == 0) return 1;                                                     //  no matches

      pp1 = matchtagstext;

      for (ii = 0; ii < nt; ii++)                                                //  make deftag list: aaaaa, bbb, cccc ...
      {
         strcpy(pp1,matchtags[ii]);
         pp1 += strlen(pp1);
         strcpy(pp1,", ");
         pp1 += 2;
      }
      
      zdialog_stuff(zd,"matchtags",matchtagstext);                               //  stuff matchtags in dialog
      return 1;
   }

   if (strmatch(event,"add"))                                                    //  enter new tag finished
   {
      zdialog_fetch(zd,"newtag",newtag,tagcc);                                   //  get finished tag
      cc1 = strlen(newtag);
      if (! cc1) return 1;
      if (newtag[cc1-1] == '\n') {                                               //  remove newline character
         cc1--;
         newtag[cc1] = 0;
      }

      for (ii = ff = 0; ii < maxtagcats; ii++)                                   //  loop all categories
      {
         pp2 = tags_deftags[ii];                                                 //  category: aaaaaa, bbbbb, ... tagN,
         if (! pp2) continue;                                                    //            |     |
         pp2 = strchr(pp2,':');                                                  //            pp1   pp2
         
         while (true)                                                            //  loop all deftags in category
         {
            pp1 = pp2 + 2;
            if (! *pp1) break;
            pp2 = strchr(pp1,',');
            if (! pp2) break;
            cc2 = pp2 - pp1;
            if (cc2 != cc1) continue;
            if (strmatchcaseN(newtag,pp1,cc1)) {                                 //  entered tag matches deftag
               strncpy(newtag,pp1,cc1);                                          //  use deftag upper/lower case
               ff = 1;
               break;
            }
         }

         if (ff) break;
      }

      if (! ff) {                                                                //  if new tag, add to defined tags
         add_deftag((char *) "nocatg",newtag);
         deftags_stuff(zd,"ALL");
      }

      add_tag(newtag,addtags,tagMcc);                                            //  add to tag add list
      zdialog_stuff(zdbatchtags,"addtags",addtags);

      zdialog_stuff(zd,"newtag","");                                             //  update dialog widgets
      zdialog_stuff(zd,"matchtags","");

      zdialog_goto(zd,"newtag");                                                 //  put focus back on newtag widget
      return 1;
   }

   return 1;
}


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

//  menu function - rename multiple tags for selected image files

namespace batchrenametags
{
   int      Ntags;                                                               //  count, 1-100
   char     *oldtags[100];                                                       //  tags to rename
   char     *newtags[100];                                                       //  corresponding new name
   #define  tpcc (tagcc+tagcc+10)
   zdialog  *zd;
}


//  menu function

void m_batch_rename_tags(GtkWidget *, cchar *menu)
{
   using namespace batchrenametags;

   void  batchrenametags_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  batchrenametags_taglist_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   batchrenametags_dialog_event(zdialog *zd, cchar *event);

   char        *file;
   int         ii, jj, kk, ff, yn, err;
   int         zstat, Nfiles, Nlist;
   GtkWidget   *widget;
   char        **filelist;
   char        *pp, *filetag;
   char        *oldtaglist[100], *newtaglist[100];
   xxrec_t     *xxrec;

   F1_help_topic = "batch_rename_tags";

   if (checkpend("all")) return;                                                 //  check nothing pending
   Fblock = 1;
   
   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable    18.07
      if (yn) index_rebuild(2,0);
      else return;
   }

   Ntags = Nfiles = 0;
   filelist = 0;

/***
       ____________________________________________________________________________
      |        Batch Rename Tags                   |                               |
      |                                            | old tag name >> new tag name  |
      | Tag [_______]  Rename to [_________]  [->] | aaaaaaaa >> bbbbbbbbbbb       |
      |                                            | ccccccccccc >> ddddddddd      |
      | Defined Tags Category [________________|v| |                               |
      | |                                        | |                               |
      | |                                        | |                               |
      | |                                        | |                               |
      | |                                        | |                               |
      | |                                        | |                               |
      | |                                        | |                               |
      | |________________________________________| |_______________________________|
      |                                                                            |
      |                                                        [Proceed] [Cancel]  |
      |____________________________________________________________________________|

***/

   zd = zdialog_new(E2X("Batch Rename Tags"),Mwin,Bproceed,Bcancel,null);
   
   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"expand");
   zdialog_add_widget(zd,"vbox","vb1","hb1",0,"expand");
   zdialog_add_widget(zd,"vbox","vb2","hb1",0,"space=8|expand");

   //  tag [_________________]  rename to [___________________]  [-->]
   zdialog_add_widget(zd,"hbox","hbtags","vb1",0,"space=3");
   zdialog_add_widget(zd,"label","lab1","hbtags","Tag","space=3");
   zdialog_add_widget(zd,"frame","frot","hbtags");
   zdialog_add_widget(zd,"label","oldtag","frot",E2X("(click defined tag)"));
   zdialog_add_widget(zd,"label","space","hbtags",0,"space=5");
   zdialog_add_widget(zd,"label","lab2","hbtags",E2X("Rename to"),"space=3");
   zdialog_add_widget(zd,"zentry","newtag","hbtags",0,"expand");
   zdialog_add_widget(zd,"label","space","hbtags",0,"space=3");
   zdialog_add_widget(zd,"button","addtags","hbtags",">>");
   
   zdialog_add_widget(zd,"hsep","hsep1","vb1",0,"space=5");
   
   //  Defined Tags Category [_____________________|v]
   zdialog_add_widget(zd,"hbox","hbdt","vb1",0);
   zdialog_add_widget(zd,"label","labdt","hbdt",E2X("Defined Tags Category"),"space=3");
   zdialog_add_widget(zd,"combo","defcats","hbdt",0,"space=5");
   zdialog_add_widget(zd,"frame","frdt","vb1",0,"expand|space=3");
   zdialog_add_widget(zd,"scrwin","swdt","frdt",0,"expand");
   zdialog_add_widget(zd,"text","deftags","swdt",0,"wrap");
   
   //  old tag name >> new tag name
   zdialog_add_widget(zd,"hbox","hblist","vb2");
   zdialog_add_widget(zd,"label","lablist","hblist",E2X("old tag name >> new tag name"),"space=10");
   zdialog_add_widget(zd,"frame","frlist","vb2",0,"expand|space=3");
   zdialog_add_widget(zd,"scrwin","swlist","frlist");
   zdialog_add_widget(zd,"text","taglist","swlist");

   load_deftags();                                                               //  stuff defined tags into dialog
   deftags_stuff(zd,"ALL");
   defcats_stuff(zd);                                                            //  and defined categories

   widget = zdialog_widget(zd,"deftags");                                        //  connect mouse to defined tags widget
   textwidget_set_callbackfunc(widget,batchrenametags_deftags_clickfunc);

   widget = zdialog_widget(zd,"taglist");                                        //  connect mouse to taglist widget
   textwidget_set_callbackfunc(widget,batchrenametags_taglist_clickfunc);

   zdialog_resize(zd,700,400);                                                   //  run dialog

   zdialog_run(zd,batchrenametags_dialog_event,"parent");
   zstat = zdialog_wait(zd);                                                     //  wait for dialog completion
   zdialog_free(zd);
   zd = 0;
   if (zstat != 1) goto cleanup;                                                 //  [cancel]

   filelist = (char **) zmalloc(Nxxrec * sizeof(char *));                        //  find all affected image files
   Nfiles = 0;
   
   popup_report_open(Mwin,"rename tags",500,300);                                //  18.01

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs 
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];   
      if (! xxrec->tags) continue;                                               //  search for tags to rename

      ff = 0;

      for (jj = 1; ; jj++) {
         pp = (char *) strField(xxrec->tags,',',jj);
         if (! pp) break;
         if (strmatch(pp,"null")) continue;
         for (kk = 0; kk < Ntags; kk++) {
            if (strmatchcase(pp,oldtags[kk])) {                                  //  this file has one or more tags
               ff = 1;                                                           //    that will be renamed
               break;
            }
         }
         if (ff) break;
      }
      
      if (ff) {
         filelist[Nfiles] = zstrdup(xxrec->file);                                //  add to list of files to process
         Nfiles++;
         popup_report_write(0,"file included: %s \n",xxrec->file);
         popup_report_bottom();                                                  //  18.07
      }
   }
   
   yn = zmessageYN(Mwin,E2X("%d tags to rename \n"
                            "in %d image files. \n"
                            "Proceed?"),Ntags,Nfiles);
   if (! yn) goto cleanup;

   for (ii = 0; ii < Nfiles; ii++)                                               //  loop all selected files
   {
      zmainloop();                                                               //  keep GTK alive 

      file = filelist[ii];                                                       //  open image file
      err = f_open(file,0,0,0);
      if (err) continue;

      popup_report_write(0,"%s \n",file);                                        //  report progress
      popup_report_bottom();                                                     //  18.07

      Nlist = 0;

      for (jj = 1; ; jj++) {                                                     //  loop file tags
         filetag = (char *) strField(meta_tags,',',jj);
         if (! filetag) break;
         for (kk = 0; kk < Ntags; kk++) {                                        //  loop tag replacement list
            if (strmatchcase(filetag,oldtags[kk])) {                             //  file tag matches tag to replace
               oldtaglist[Nlist] = oldtags[kk];                                  //  save old and new tags 
               newtaglist[Nlist] = newtags[kk];
               Nlist++;
               break;                                                            //  next file tag
            }
         }
      }

      for (jj = 0; jj < Nlist; jj++)                                             //  remove old tags
         err = del_tag(oldtaglist[jj],meta_tags);

      for (jj = 0; jj < Nlist; jj++) {                                           //  add new tags
         if (! newtaglist[jj]) continue;                                         //  must be after removals
         popup_report_write(0,"%s \n",newtaglist[jj]);
         err = add_tag(newtaglist[jj],meta_tags,tagFcc);
         if (err && err != 1) popup_report_write(1,"ERROR \n");                  //  ignore already there, else report
         popup_report_bottom();                                                  //  18.07
      }

      save_filemeta(file);                                                       //  save tag changes
   }

   popup_report_write(0,"%s \n",Bcompleted);
   popup_report_bottom();                                                        //  18.07

cleanup:                                                                         //  free resources

   Fblock = 0;
   
   for (ii = 0; ii < Ntags; ii++) {
      zfree(oldtags[ii]);
      zfree(newtags[ii]);
   }
   
   for (ii = 0; ii < Nfiles; ii++)
      zfree(filelist[ii]);
   if (filelist) zfree(filelist);
      
   return;
}


//  a defined tag was clicked

void batchrenametags_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace batchrenametags;

   char     *txtag, end;
   char     tagname[tagcc];

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }
   
   txtag = textwidget_word(widget,line,pos,",;:",end);                           //  clicked word
   if (! txtag || end == ':') return;                                            //  tag category clicked, ignore

   snprintf(tagname,tagcc," %s ",txtag);                                         //  add spaces for appearance
   zdialog_stuff(zd,"oldtag",tagname);
   zdialog_stuff(zd,"newtag","");

   zfree(txtag);
   return;
}


//  a tag list line was clicked

void batchrenametags_taglist_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace batchrenametags;
   
   int      ii;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }
   
   if (line >= Ntags) return;
   
   for (ii = line; ii < Ntags-1; ii++) {                                         //  remove tags pair corresponding
      oldtags[ii] = oldtags[ii+1];                                               //    to the line clicked
      newtags[ii] = newtags[ii+1];
   }
   Ntags--;
   
   widget = zdialog_widget(zd,"taglist");                                        //  rewrite dialog tag list
   textwidget_clear(widget);
   for (int ii = 0; ii < Ntags; ii++)
      textwidget_append2(widget,0,"%s >> %s\n",oldtags[ii],newtags[ii]);
   
   return;
}


//  batch rename tags dialog event function

int batchrenametags_dialog_event(zdialog *zd, cchar *event)
{
   using namespace batchrenametags;

   char        catgname[tagcc];
   char        oldtag[tagcc], newtag[tagcc];
   GtkWidget   *widget;

   if (strmatch(event,"cancel")) zd->zstat = 2;

   if (zd->zstat) return 1;                                                      //  dialog completed

   if (strmatch(event,"defcats")) {                                              //  new tag category selection
      zdialog_fetch(zd,"defcats",catgname,tagcc);
      deftags_stuff(zd,catgname);
   }
   
   if (strmatch(event,"addtags")) {                                              //  [ --> ] button pressed
      zdialog_fetch(zd,"oldtag",oldtag,tagcc);                                   //  save new pair of tag names
      zdialog_fetch(zd,"newtag",newtag,tagcc);
      strTrim2(oldtag);
      strTrim2(newtag);
      if (*oldtag <= ' ' || *newtag <= ' ') return 1;
      if (Ntags == 100) {
         zmessageACK(Mwin,E2X("max tags exceeded"));
         return 1;
      }
      oldtags[Ntags] = zstrdup(oldtag);
      newtags[Ntags] = zstrdup(newtag);
      Ntags++;
   }
   
   widget = zdialog_widget(zd,"taglist");                                        //  rewrite dialog tag list
   textwidget_clear(widget);
   for (int ii = 0; ii < Ntags; ii++) 
      textwidget_append2(widget,0,"%s >> %s\n",oldtags[ii],newtags[ii]);

   return 1;
}


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

//  batch change or shift photo date/time

void m_batch_photo_date_time(GtkWidget *, cchar *menu)                           //  18.01
{
   int  batch_photo_time_dialog_event(zdialog *zd, cchar *event);

   cchar       *keyname[1] = { "DateTimeOriginal" };
   char        *keyvalue[1];
   char        *file, olddatetime[24], newdatetime[24];                          //  exif format "yyyy:mm:dd hh:mm:ss"
   int         ii, nn, cc, err, zstat;
   int         Fyearonly, Fdateonly;
   int         Fsetnew, Fshift, Ftest;                                           //  check boxes
   time_t      timep;
   struct tm   DTold, DTnew;                                                     //  old and new date/time
   int         s_years, s_mons, s_mdays, s_hours, s_mins, s_secs;                //  shift amounts
   zdialog     *zd;

   F1_help_topic = "batch_photo_date";

   if (checkpend("all")) return;                                                 //  check nothing pending
   Fblock = 1;

/***
       __________________________________________________
      |            Batch Photo Date/Time                 |
      |                                                  |
      |  [Select Files]  NN files selected               |
      |                                                  |
      | [x] set a new date/time: [_____________________] |
      |                           (yyyy-mm-dd hh:mm:ss)  |
      |                                                  |
      | [x] shift existing date/time:                    |
      |      years [__]  months [__]  days [__]          |
      |      hours [__]  minutes [__]  seconds [__]      |
      |                                                  |
      | [x] test: show changes, do not update files      |
      |                                                  |
      |                               [proceed] [cancel] |
      |__________________________________________________|

***/


   zd = zdialog_new(E2X("Batch Photo Date/Time"),Mwin,Bproceed,Bcancel,null);

   zdialog_add_widget(zd,"hbox","hbfiles","dialog",0,"space=3");
   zdialog_add_widget(zd,"button","files","hbfiles",Bselectfiles,"space=5");
   zdialog_add_widget(zd,"label","labcount","hbfiles",Bnofileselected,"space=10");

   zdialog_add_widget(zd,"hsep","sep1","dialog",0,"space=5");
   zdialog_add_widget(zd,"hbox","hbsetnew","dialog",0,"space=3");
   zdialog_add_widget(zd,"check","Fsetnew","hbsetnew",E2X("set a new date/time:"),"space=3");
   zdialog_add_widget(zd,"zentry","newdatetime","hbsetnew",0,"expand|size=15");
   zdialog_add_widget(zd,"hbox","hbsetnew2","dialog");
   zdialog_add_widget(zd,"label","labspace","hbsetnew2","","expand");
   zdialog_add_widget(zd,"label","labtemplate","hbsetnew2","yyyy-mm-dd hh:mm[:ss]","space=5");
   
   zdialog_add_widget(zd,"hsep","sep1","dialog",0,"space=5");
   zdialog_add_widget(zd,"hbox","hbshift1","dialog",0,"space=3");
   zdialog_add_widget(zd,"check","Fshift","hbshift1",E2X("shift existing date/time:"),"space=3");

   zdialog_add_widget(zd,"hbox","hbshift2","dialog");
   zdialog_add_widget(zd,"label","space","hbshift2",0,"space=10");
   zdialog_add_widget(zd,"label","labyears","hbshift2","years","space=5");
   zdialog_add_widget(zd,"zspin","s_years","hbshift2","-99|+99|1|0");
   zdialog_add_widget(zd,"label","space","hbshift2",0,"space=5");
   zdialog_add_widget(zd,"label","labmons","hbshift2","months","space=5");
   zdialog_add_widget(zd,"zspin","s_mons","hbshift2","-11|+11|1|0");
   zdialog_add_widget(zd,"label","space","hbshift2",0,"space=5");
   zdialog_add_widget(zd,"label","labmdays","hbshift2","days","space=5");
   zdialog_add_widget(zd,"zspin","s_mdays","hbshift2","-30|+30|1|0");

   zdialog_add_widget(zd,"hbox","hbshift3","dialog");
   zdialog_add_widget(zd,"label","space","hbshift3",0,"space=10");
   zdialog_add_widget(zd,"label","labhours","hbshift3","hours","space=5");
   zdialog_add_widget(zd,"zspin","s_hours","hbshift3","-23|+23|1|0");
   zdialog_add_widget(zd,"label","space","hbshift3",0,"space=5");
   zdialog_add_widget(zd,"label","labmins","hbshift3","minutes","space=5");
   zdialog_add_widget(zd,"zspin","s_mins","hbshift3","-59|+59|1|0");
   zdialog_add_widget(zd,"label","space","hbshift3",0,"space=5");
   zdialog_add_widget(zd,"label","labsecs","hbshift3","seconds","space=5");
   zdialog_add_widget(zd,"zspin","s_secs","hbshift3","-59|+59|1|0");
   
   zdialog_add_widget(zd,"hsep","sep1","dialog",0,"space=5");
   zdialog_add_widget(zd,"hbox","hbtest","dialog",0,"space=5");
   zdialog_add_widget(zd,"check","Ftest","hbtest",E2X("test: show changes, do not update files"),"space=3");

   zdialog_restore_inputs(zd);
   zstat = zdialog_run(zd,batch_photo_time_dialog_event,"parent");

retry:

   zstat = zdialog_wait(zd);                                                     //  wait for dialog, get status
   if (zstat != 1) {                                                             //  not [proceed]
      zdialog_free(zd);                                                          //  cancel
      Fblock = 0;
      return;
   }

   zd->zstat = 0;                                                                //  keep dialog active

   zdialog_fetch(zd,"Fsetnew",Fsetnew);                                          //  checkboxes
   zdialog_fetch(zd,"Fshift",Fshift);
   zdialog_fetch(zd,"Ftest",Ftest);
   
   if (Fsetnew + Fshift != 1) {
      zmessageACK(Mwin,"please make a choice");
      goto retry;
   }
   
   if (GScount == 0) {
      zmessageACK(Mwin,E2X("no files selected"));
      goto retry;
   }

   Fyearonly = Fdateonly = 0;
   
   if (Fsetnew)                                                                  //  input is new date/time
   {
      zdialog_fetch(zd,"newdatetime",newdatetime,24);
      strTrim2(newdatetime);                                                     //  strip leading and trailing blanks
      cc = strlen(newdatetime);
      
      if (cc == 4) {                                                             //  have only "yyyy"
         strcat(newdatetime,"-01-01 00:00:00");                                  //  append "-01-01 00:00:00"
         Fyearonly = 1;
         cc = 19;
      }

      if (cc == 10) {                                                            //  have only "yyyy-mm-dd"
         strcat(newdatetime," 00:00:00");                                        //  append " 00:00:00"
         Fdateonly = 1;                                                          //  flag, change date only
         cc = 19;
      }
      
      if (cc == 16) {                                                            //  have only "yyyy-mm-dd hh:mm"
         strcat(newdatetime,":00");                                              //  append ":00" 
         cc = 19;
      }
      
      if (cc != 19) {                                                            //  must have yyyy-mm-dd hh:mm:ss
         zmessageACK(Mwin,E2X("invalid date/time format"));
         goto retry;
      }
      
      nn = sscanf(newdatetime,"%d-%d-%d %d:%d:%d",                               //  yyyy-mm-dd hh:mm:ss >> DTnew
                     &DTnew.tm_year, &DTnew.tm_mon, &DTnew.tm_mday, 
                     &DTnew.tm_hour, &DTnew.tm_min, &DTnew.tm_sec);
      DTnew.tm_mon -= 1;                                                         //  mktime month is 0-11

      if (nn != 6) {                                                             //  check input format
         zmessageACK(Mwin,E2X("invalid date/time format"));
         goto retry;
      }
      
      timep = mktime(&DTnew);                                                    //  DTnew >> timep
      if (timep < 0) {                                                           //  validate DTnew by validating timep
         zmessageACK(Mwin,E2X("invalid date/time format"));
         goto retry;
      }
   }                                                                             //  DTnew is final value to use
   
   if (Fshift)
   {
      zdialog_fetch(zd,"s_years",s_years);                                       //  inputs are shifted date/time values
      zdialog_fetch(zd,"s_mons",s_mons);
      zdialog_fetch(zd,"s_mdays",s_mdays);
      zdialog_fetch(zd,"s_hours",s_hours);
      zdialog_fetch(zd,"s_mins",s_mins);
      zdialog_fetch(zd,"s_secs",s_secs);
   }
   
   zdialog_free(zd);

   popup_report_open(Mwin,"Batch Photo date/time Update",500,200);               //  start popup report
   
   if (Fshift) {
      popup_report_write(0,"changes: year mon day  hours mins secs \n");
      popup_report_write(0,"         %4d %3d %3d  %5d %4d %4d \n",
                          s_years,s_mons,s_mdays,s_hours,s_mins,s_secs);
      popup_report_bottom();                                                     //  18.07
   }

   for (ii = 0; ii < GScount; ii++)                                              //  loop all selected files
   {
      file = GSfiles[ii];
      err = f_open(file,0,0,0);                                                  //  open image file
      if (err) continue;

      popup_report_write(0,"\n");                                                //  report progress
      popup_report_write(0,"%s \n",file);
      popup_report_bottom();                                                     //  18.07

      exif_get(curr_file,keyname,(char **) keyvalue,1);                          //  metadata >> yyyy:mm:dd hh:mm:ss
      if (! keyvalue[0] && Fshift) {                                             //  ignore if Fsetnew                  18.07
         popup_report_write(0,"  *** no date/time available \n");
         popup_report_bottom();                                                  //  18.07
         continue;
      }
      
      if (keyvalue[0]) {                                                         //  18.07
         strncpy0(olddatetime,keyvalue[0],20);                                   //  yyyy:mm:dd hh:mm:ss
         zfree(keyvalue[0]);
      }
      else strcpy(olddatetime,"0000:01:01 00:00:00");                            //  missing old date/time              18.07

      nn = sscanf(olddatetime,"%d:%d:%d %d:%d:%d",                               //  yyyy-mm-dd hh:mm:ss >> DTnew
                     &DTold.tm_year, &DTold.tm_mon, &DTold.tm_mday, 
                     &DTold.tm_hour, &DTold.tm_min, &DTold.tm_sec);
      DTold.tm_mon -= 1;                                                         //  mktime month is 0-11

      if (nn != 6 && Fshift) {
         popup_report_write(0,"  *** EXIF date/time invalid \n");
         popup_report_bottom();                                                  //  18.07
         continue;
      }
      
      if (nn != 6) strcpy(olddatetime,"0000:01:01 00:00:00");                    //  missing old date/time              18.07

      if (Fsetnew)                                                               //  set new date/time
      {
         if (Fyearonly)                                                          //  change year only, leave rest
         {
            DTnew.tm_mon = DTold.tm_mon;                                         //  >> revised DTnew
            DTnew.tm_mday = DTold.tm_mday;                                       //  set month/day/hour/min/sec only
            DTnew.tm_hour = DTold.tm_hour;                                       //  year remains fixed
            DTnew.tm_min = DTold.tm_min;
            DTnew.tm_sec = DTold.tm_sec;
         }

         if (Fdateonly)                                                          //  change year/mon/day only, leave time
         {
            DTnew.tm_hour = DTold.tm_hour;                                       //  >> revised DTnew
            DTnew.tm_min = DTold.tm_min;                                         //  set hour/min/sec only
            DTnew.tm_sec = DTold.tm_sec;                                         //  year/mon/day remains fixed
         }
      }
      
      if (Fshift)                                                                //  shift existing date/time values
      {
         DTnew.tm_year = DTold.tm_year + s_years;
         DTnew.tm_mon = DTold.tm_mon + s_mons;
         DTnew.tm_mday = DTold.tm_mday + s_mdays;
         DTnew.tm_hour = DTold.tm_hour + s_hours;
         DTnew.tm_min = DTold.tm_min + s_mins;
         DTnew.tm_sec = DTold.tm_sec + s_secs;
      }

      timep = mktime(&DTnew);
      if (timep < 0) {
         popup_report_write(0," %s  *** date/time conversion failed \n",olddatetime);
         popup_report_bottom();                                                  //  18.07
         continue;
      }

      DTnew = *localtime(&timep);

      snprintf(newdatetime,20,"%04d:%02d:%02d %02d:%02d:%02d",                   //  DTnew >> yyyy:mm:dd hh:mm:ss
                            DTnew.tm_year, DTnew.tm_mon+1, DTnew.tm_mday,        //  (tm_mon 0-11 >> 1-12)
                            DTnew.tm_hour, DTnew.tm_min, DTnew.tm_sec);
      
      olddatetime[4] = olddatetime[7] = newdatetime[4] = newdatetime[7] = '-';   //  format: yyyy-mm-dd
      popup_report_write(0," %s  %s \n",olddatetime,newdatetime);
      popup_report_bottom();                                                     //  18.07
      
      if (Ftest) continue;                                                       //  test only, no file updates

      newdatetime[4] = newdatetime[7] = ':';                                     //  format: yyyy:mm:dd for EXIF
      keyvalue[0] = (char *) &newdatetime;
      err = exif_put(curr_file,keyname,(cchar **) keyvalue,1);                   //  yyyy:mm:dd hh:mm:ss >> metadata

      load_filemeta(curr_file);                                                  //  get all indexed data for file

      snprintf(meta_pdate,16,"%04d%02d%02d%02d%02d%02d",                         //  update photo date, yyyymmddhhmmss
                            DTnew.tm_year, DTnew.tm_mon+1, DTnew.tm_mday,        //  (tm_mon 0-11 >> 1-12)
                            DTnew.tm_hour, DTnew.tm_min, DTnew.tm_sec);
      update_image_index(curr_file);                                             //  update image index rec.

      zmainloop();                                                               //  keep GTK alive
   }

   popup_report_write(1,"\n *** %s \n",Bcompleted);
   popup_report_bottom();                                                        //  18.07
   gallery(0,"paint",-1);
   
   Fblock = 0;

   m_batch_photo_date_time(0,0);                                                 //  repeat
   return;
}


//  dialog event and completion callback function

int batch_photo_time_dialog_event(zdialog *zd, cchar *event)
{
   char     countmess[80];
   int      nn;

   if (strmatch(event,"files"))                                                  //  select images to process
   {
      zdialog_show(zd,0);                                                        //  hide parent dialog
      gallery_select();                                                          //  get new file list
      zdialog_show(zd,1);

      snprintf(countmess,80,Bfileselected,GScount);
      zdialog_stuff(zd,"labcount",countmess);
   }

   if (strmatch(event,"setnew")) {                                               //  toggle option, set new date/time
      zdialog_fetch(zd,"setnew",nn);
      if (nn) zdialog_stuff(zd,"shift",0);
   }

   if (strmatch(event,"shift")) {                                                //  toggle option, shift hours
      zdialog_fetch(zd,"shift",nn);
      if (nn) zdialog_stuff(zd,"setnew",0);
   }

   return 1;
}


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

//  batch add or change any EXIF/IPTC metadata

namespace batchchangemeta
{
   zdialog     *zd;
}


//  menu function

void m_batch_change_metadata(GtkWidget *, cchar *menu)                           //  overhauled
{
   using namespace batchchangemeta;

   int  batch_change_metadata_dialog_event(zdialog *zd, cchar *event);
   void batch_change_metadata_clickfunc(GtkWidget *, int line, int pos, int kbkey);

   int         ii, jj, err, zstat, nkeys;
   char        keynameN[12] = "keynameN", keyvalueN[12] = "keyvalueN";
   char        keyname[40], keyvalue[exif_maxcc];
   cchar       *pp1[10], *pp2[10];
   char        *file, *pp;
   GtkWidget   *mtext;
   char        filename[200], buff[100];
   FILE        *fid;

   F1_help_topic = "batch_change_metadata";

   if (checkpend("all")) return;                                                 //  check nothing pending
   Fblock = 1;

/**
       _________________________________________________________________
      |  Click to Select   |        Batch Add/Change Metadata           |
      |                    |                                            |
      |  (metadata list)   |  [Select Files]  NN files selected         |
      |                    |                                            |
      |                    |     key name           key value           |        
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |  [______________]  [_____________________] |
      |                    |                                            |
      |                    |               [Full List] [apply] [cancel] |
      |____________________|____________________________________________|

**/

   zd = zdialog_new(E2X("Batch Add/Change Metadata"),Mwin,E2X("Full List"),Bapply,Bcancel,null);
   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"expand");
   zdialog_add_widget(zd,"vbox","vb1","hb1");
   zdialog_add_widget(zd,"vbox","vb2","hb1",0,"expand|space=5");

   zdialog_add_widget(zd,"label","lab1","vb1",E2X("click to select"),"size=30|space=3");
   zdialog_add_widget(zd,"frame","fr1","vb1",0,"expand");
   zdialog_add_widget(zd,"scrwin","scr1","fr1");
   zdialog_add_widget(zd,"text","mtext","scr1");

   zdialog_add_widget(zd,"hbox","hbfiles","vb2",0,"space=3");
   zdialog_add_widget(zd,"button","files","hbfiles",Bselectfiles,"space=5");
   zdialog_add_widget(zd,"label","labcount","hbfiles",Bnofileselected,"space=10");
   
   zdialog_add_widget(zd,"hbox","hbkeys","vb2",0,"space=5");
   zdialog_add_widget(zd,"vbox","vbname","hbkeys");
   zdialog_add_widget(zd,"vbox","vbvalue","hbkeys",0,"expand");
   zdialog_add_widget(zd,"label","labkey","vbname",E2X("key name"));
   zdialog_add_widget(zd,"label","labdata","vbvalue",E2X("key value"));
   zdialog_add_widget(zd,"zentry","keyname0","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname1","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname2","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname3","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname4","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname5","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname6","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname7","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname8","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyname9","vbname",0,"size=20");
   zdialog_add_widget(zd,"zentry","keyvalue0","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue1","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue2","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue3","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue4","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue5","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue6","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue7","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue8","vbvalue",0,"size=20|expand");
   zdialog_add_widget(zd,"zentry","keyvalue9","vbvalue",0,"size=20|expand");
   
   mtext = zdialog_widget(zd,"mtext");                                           //  make clickable metadata list
   textwidget_clear(mtext);

   snprintf(filename,200,"%s/metadata_short_list",get_zhomedir());
   fid = fopen(filename,"r");
   if (! fid) {
      zmessageACK(Mwin,"%s \n %s",filename,strerror(errno));
      return;
   }

   while (true) {
      pp = fgets_trim(buff,100,fid,1);
      if (! pp) break;
      textwidget_append(mtext,0,"%s \n",buff);
   }
   fclose(fid);

   textwidget_set_callbackfunc(mtext,batch_change_metadata_clickfunc);

   gallery_select_clear();                                                       //  clear gallery_select() file list

   nkeys = 0;

   zstat = zdialog_run(zd,batch_change_metadata_dialog_event,"parent");          //  run dialog

retry:
   zstat = zdialog_wait(zd);                                                     //  wait for completion
   if (zstat != 2) goto cleanup;                                                 //  not [apply]
   
   for (ii = jj = 0; ii < 10; ii++)
   {
      keynameN[7] = '0' + ii;
      keyvalueN[8] = '0' + ii;
      zdialog_fetch(zd,keynameN,keyname,40);
      zdialog_fetch(zd,keyvalueN,keyvalue,exif_maxcc);
      strCompress(keyname);
      if (*keyname <= ' ') continue;
      pp1[jj] = zstrdup(keyname);
      pp2[jj] = zstrdup(keyvalue);
      jj++;
   }
   nkeys = jj;

   if (nkeys == 0) {
      zmessageACK(Mwin,E2X("enter key names"));
      zd->zstat = 0;
      goto retry;
   }
      
   if (GScount == 0) {
      zmessageACK(Mwin,E2X("no files selected"));
      zd->zstat = 0;
      goto retry;
   }
   
   popup_report_open(Mwin,"Batch Metadata",500,200);                             //  popup report
   
   for (ii = 0; ii < nkeys; ii++)
   {
      if (*pp2[ii]) popup_report_write(0,"%s = %s \n",pp1[ii],pp2[ii]);
      else popup_report_write(0,"%s = DELETED \n",pp1[ii]);
   }
   
   ii = zdialog_choose(Mwin,"parent",Bproceed,Bproceed,Bcancel,null);
   if (ii != 1) {
      zd->zstat = 0;                                                             //  cancel
      popup_report_close(0);
      popup_report_bottom();                                                     //  18.07
      goto retry;
   }

   zdialog_free(zd);
   zd = 0;

   for (ii = 0; ii < GScount; ii++)                                              //  loop all selected files
   {
      zmainloop();                                                               //  keep GTK alive

      file = GSfiles[ii];                                                        //  display image
      err = f_open(file,0,0,0);
      if (err) continue;

      popup_report_write(0,"%s \n",file);                                        //  report progress
      popup_report_bottom();                                                     //  18.07

      err = exif_put(curr_file,pp1,pp2,nkeys);                                   //  change metadata in image file

      load_filemeta(curr_file);                                                  //  update image index in case
      update_image_index(curr_file);                                             //    indexed metadata updated

      if (zdexifview) meta_view(0);                                              //  update exif view if active
   }

   popup_report_write(0,"%s \n",Bcompleted);
   popup_report_bottom();                                                        //  18.07

cleanup:

   if (zd) zdialog_free(zd);                                                     //  kill dialog
   zd = 0;

   for (ii = 0; ii < nkeys; ii++) {                                              //  free memory
      zfree((char *) pp1[ii]);
      zfree((char *) pp2[ii]);
   }
   nkeys = 0;

   Fblock = 0;
   return;
}


//  dialog event and completion callback function

int  batch_change_metadata_dialog_event(zdialog *zd, cchar *event)
{
   using namespace batchchangemeta;

   char        countmess[80];

   if (zd->zstat == 1)                                                           //  full list
   {
      zd->zstat = 0;                                                             //  keep dialog active
      zmessageACK(Mwin,E2X("The command: $ man Image::ExifTool::TagNames \n"
                           "will show over 15000 \"standard\" tag names"));
   }
   
   if (strmatch(event,"files"))                                                  //  select images to process
   {
      gallery_select_clear();                                                    //  clear gallery_select() file list

      zdialog_show(zd,0);                                                        //  hide parent dialog
      gallery_select();                                                          //  get new list
      zdialog_show(zd,1);

      snprintf(countmess,80,Bfileselected,GScount);
      zdialog_stuff(zd,"labcount",countmess);
   }
   
   return 1;
}


//  get clicked tag name from short list and insert into dialog

void batch_change_metadata_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace batchchangemeta;

   int      ii;
   char     *pp;
   char     keynameX[12] = "keynameX";
   char     keyname[60];

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   pp = textwidget_line(widget,line,1);                                          //  get clicked line, highlight
   if (! pp || ! *pp) return;
   textwidget_highlight_line(widget,line);
   
   for (ii = 0; ii < 10; ii++) {                                                 //  find 1st empty dialog key name
      keynameX[7] = '0' + ii;
      zdialog_fetch(zd,keynameX,keyname,60);
      if (*keyname <= ' ') break;
   }
   
   if (ii < 10) zdialog_stuff(zd,keynameX,pp);
   return;
}


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

//  batch report metadata for selected image files

namespace batchreportmeta
{
   char     filex[200];                                                          //  file for metadata item list
}


//  menu function

void m_batch_report_metadata(GtkWidget *, cchar *menu)
{
   using namespace batchreportmeta;

   int  batch_report_metadata_dialog_event(zdialog *zd, cchar *event);

   zdialog     *zd;
   char        buff[200];
   char        *file, *pp;
   FILE        *fid = 0;
   int         zstat, ff, ii, err;
   int         nkx = 0;
   char        *keynamex[NK], *keyvalx[NK];
   
   F1_help_topic = "batch_report_metadata";

   snprintf(filex,200,"%s/metadata_report_items",get_zhomedir());                //  file for items to report

   gallery_select_clear();                                                       //  clear gallery_select() file list

/***
          ____________________________________________
         |           Batch Report Metadata            |
         |                                            |
         |  [Select Files]  NN files selected         |
         |  [Edit] list of reported metadata items    |
         |                                            |
         |                         [proceed] [cancel] |
         |____________________________________________|

***/

   zd = zdialog_new(E2X("Batch Report Metadata"),Mwin,Bproceed,Bcancel,null);
   zdialog_add_widget(zd,"hbox","hbfiles","dialog",0,"space=3");
   zdialog_add_widget(zd,"button","files","hbfiles",Bselectfiles,"space=5");
   zdialog_add_widget(zd,"label","labcount","hbfiles",Bnofileselected,"space=10");
   zdialog_add_widget(zd,"hbox","hbedit","dialog",0,"space=3");
   zdialog_add_widget(zd,"button","edit","hbedit",Bedit,"space=5");
   zdialog_add_widget(zd,"label","labedit","hbedit","list of reported metadata items","space=10");

   zstat = zdialog_run(zd,batch_report_metadata_dialog_event,"parent");          //  run dialog
   zstat = zdialog_wait(zd);                                                     //  wait for completion
   if (zstat != 1) goto cleanup;                                                 //  cancel
   zdialog_free(zd);
   
   if (GScount == 0) {
      zmessageACK(Mwin,E2X("no files selected"));
      return;
   }

   fid = fopen(filex,"r"); 
   if (! fid) {
      zmessageACK(Mwin,"no metadata items to report");
      return;
   }

   for (nkx = ii = 0; ii < 20; ii++)                                             //  read items to report
   {
      pp = fgets_trim(buff,100,fid,1);
      if (! pp) break;
      strCompress(pp);
      if (*pp <= ' ') continue;
      if (strmatchN(pp,"enteritems",5)) continue;
      keynamex[nkx] = zstrdup(pp);
      nkx++;
   }
   fclose(fid);
   
   if (! nkx) {
      zmessageACK(Mwin,"no metadata items to report");
      return;
   }

   popup_report_open(Mwin,"metadata report",600,400);                            //  17.08

   for (ff = 0; ff < GScount; ff++)                                              //  loop selected files
   {
      zmainloop(20);                                                             //  keep GTK alive

      file = GSfiles[ff];
      popup_report_write(0,"%s \n",file);                                        //  17.08

      err = exif_get(file,(cchar **) keynamex,keyvalx,nkx);                      //  get all report items
      if (err) {
         zmessageACK(Mwin,"exif failure");
         goto cleanup;
      }

      for (ii = 0; ii < nkx; ii++)                                               //  output keyword names and values
         if (keyvalx[ii]) 
            popup_report_write(0,"%-24s : %s \n",keynamex[ii],keyvalx[ii]);      //  17.08

      for (ii = 0; ii < nkx; ii++)                                               //  free memory
         if (keyvalx[ii]) zfree(keyvalx[ii]);
      
      popup_report_write(0,"\n");                                                //  blank line separator
      popup_report_bottom();                                                     //  18.07
   }
   
cleanup:
   for (ii = 0; ii < nkx; ii++)                                                  //  free memory
      zfree(keynamex[ii]);
   return;
}


//  dialog event and completion function

int  batch_report_metadata_dialog_event(zdialog *zd, cchar *event)
{
   using namespace batchreportmeta;

   char     countmess[80];
   char     *itemlist[Mxmeta], *pp, buff[100];
   FILE     *fid;
   int      ii;
   
   if (zd->zstat) zdialog_destroy(zd);

   if (strmatch(event,"files"))                                                  //  select images to process
   {
      gallery_select_clear();                                                    //  clear gallery_select() file list

      zdialog_show(zd,0);                                                        //  hide parent dialog
      gallery_select();                                                          //  get new list
      zdialog_show(zd,1);

      snprintf(countmess,80,Bfileselected,GScount);
      zdialog_stuff(zd,"labcount",countmess);
   }

   if (strmatch(event,"edit"))                                                   //  select metadata items to report
   {
      itemlist[0] = 0;                                                           //  empty list

      fid = fopen(filex,"r");                                                    //  read file of extra metadata items  18.01
      if (fid) {
         for (ii = 0; ii < Mxmeta; ii++) {
            pp = fgets_trim(buff,100,fid,1);
            if (! pp) break;
            if (*pp <= ' ') continue;
            itemlist[ii] = zstrdup(pp);
         }
         
         itemlist[ii] = 0;                                                       //  mark EOL
         fclose(fid);
      }

      select_meta_keys(itemlist,0);                                              //  user edit of extras list           18.01
      
      fid = fopen(filex,"w");                                                    //  update extras list file            18.01
      if (! fid) {
         zmessageACK(Mwin,"%s \n %s",filex,strerror(errno));
         return 1;
      }
      
      for (ii = 0; ii < Mxmeta; ii++)
      {
         if (! itemlist[ii]) break;
         fprintf(fid,"%s\n",itemlist[ii]);
      }

      fclose(fid);
   }

   return 1;
}


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

//  batch geotags - set geotags for multiple image files

void m_batch_geotags(GtkWidget *, cchar *menu)
{
   int   batch_geotags_dialog_event(zdialog *zd, cchar *event);

   cchar       *title = E2X("Batch Geotags");
   int         ii, err;
   char        *file;
   char        location[100], country[100];
   char        lati[20], longi[20];
   cchar       *mapquest1 = "Geocoding web service courtesy of";
   cchar       *mapquest2 = "http://www.mapquest.com";
   zdialog     *zd;

   F1_help_topic = "batch_geotags";

   if (! init_geolocs()) return;                                                 //  initialize geotags
   if (checkpend("all")) return;                                                 //  check nothing pending (block below)

/**
                      Batch Geotags

            [select files]  NN files selected
            location [______________]  country [______________]
            latitude [_______] longitude [_______]

            [find] [web] [proceed] [cancel]
**/

   zd = zdialog_new(title,Mwin,Bfind,Bweb,Bproceed,Bcancel,null);

   zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
   zdialog_add_widget(zd,"button","files","hb1",Bselectfiles,"space=10");
   zdialog_add_widget(zd,"label","labcount","hb1",Bnofileselected,"space=10");
   zdialog_add_widget(zd,"hbox","hb2","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labloc","hb2",E2X("location"),"space=5");
   zdialog_add_widget(zd,"zentry","location","hb2",0,"expand");
   zdialog_add_widget(zd,"label","space","hb2",0,"space=5");
   zdialog_add_widget(zd,"label","labcountry","hb2",E2X("country"),"space=5");
   zdialog_add_widget(zd,"zentry","country","hb2",0,"expand");
   zdialog_add_widget(zd,"hbox","hb3","dialog");
   zdialog_add_widget(zd,"label","lablat","hb3","Latitude","space=3");
   zdialog_add_widget(zd,"zentry","lati","hb3",0,"size=10");
   zdialog_add_widget(zd,"label","space","hb3",0,"space=5");
   zdialog_add_widget(zd,"label","lablong","hb3","Longitude","space=3");
   zdialog_add_widget(zd,"zentry","longi","hb3",0,"size=10");
   zdialog_add_widget(zd,"hbox","hbmq","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labmq","hbmq",mapquest1,"space=3");
   zdialog_add_widget(zd,"link","MapQuest","hbmq",mapquest2);

   gallery_select_clear();                                                       //  clear gallery_select() file list

   zd_mapgeotags = zd;                                                           //  activate map clicks

   zdialog_run(zd,batch_geotags_dialog_event,"parent");                          //  run dialog
   zdialog_wait(zd);                                                             //  wait for dialog completion

   if (zd->zstat != 3) goto cleanup;                                             //  status not [proceed]
   if (! GScount) goto cleanup;                                                  //  no files selected

   zdialog_fetch(zd,"location",location,100);                                    //  get location from dialog
   zdialog_fetch(zd,"country",country,100);
   zdialog_fetch(zd,"lati",lati,20);                                             //  and latitude, longitude
   zdialog_fetch(zd,"longi",longi,20);
   
   zd_mapgeotags = 0;                                                            //  deactivate map clicks
   zdialog_free(zd);                                                             //  kill dialog

   if (GScount == 0) goto cleanup;

   if (checkpend("all")) goto cleanup;                                           //  check nothing pending
   Fblock = 1;

   popup_report_open(Mwin,"Adding Geotags",500,200);                             //  status monitor popup window

   for (ii = 0; ii < GScount; ii++)                                              //  loop all selected files
   {
      zmainloop();                                                               //  keep GTK alive

      file = GSfiles[ii];                                                        //  display image
      err = f_open(file,0,0,0);
      if (err) continue;

      if (*location > ' ') strncpy0(meta_location,location,100);                 //  save geotags in image file EXIF
      if (*country > ' ') strncpy0(meta_country,country,100);                    //    and in search-index file
      if (*lati > ' ') strncpy0(meta_lati,lati,20);                              //  do not stuff missing data          18.01
      if (*longi > ' ') strncpy0(meta_longi,longi,20);

      Fmetamod++;
      save_filemeta(file);                                                       //  update file metadata

      popup_report_write(0,"%s \n",file);                                        //  report progress
      popup_report_bottom();                                                     //  18.07
   }

   popup_report_write(0,"%s \n",Bcompleted);
   popup_report_bottom();                                                        //  18.07

cleanup:

   Fblock = 0;
   zd_mapgeotags = 0;                                                            //  deactivate map clicks
   if (zd) zdialog_free(zd);

   return;
}


//  batch_geotags dialog event function

int batch_geotags_dialog_event(zdialog *zd, cchar *event)
{
   int      yn, zstat, err;
   char     countmess[80];
   char     location[100], country[100];
   char     lati[20], longi[20];
   cchar    *errmess;
   float    flati, flongi;
   
   if (strmatch(event,"files"))                                                  //  select images to add tags
   {
      gallery_select_clear();                                                    //  clear gallery_select() file list

      zdialog_show(zd,0);                                                        //  hide parent dialog
      gallery_select();                                                          //  get file list from user
      zdialog_show(zd,1);

      snprintf(countmess,80,Bfileselected,GScount);
      zdialog_stuff(zd,"labcount",countmess);
   }

   if (! zd->zstat) return 1;                                                    //  wait for action button

   zstat = zd->zstat;
   zd->zstat = 0;                                                                //  keep dialog active

   if (zstat == 1)                                                               //  [find]
   {
      find_location(zd);                                                         //  find location data via user
      return 1;
   }

   else if (zstat == 2)                                                          //  [web]
   {
      errmess = web_geocode(zd);                                                 //  look-up in web service
      if (errmess) zmessageACK(Mwin,errmess);                                    //  fail
   }

   else if (zstat == 3)                                                          //  [proceed]
   {
      zdialog_fetch(zd,"location",location,100);                                 //  get location from dialog
      zdialog_fetch(zd,"country",country,100);
      zdialog_fetch(zd,"lati",lati,20);
      zdialog_fetch(zd,"longi",longi,20);
      *location = toupper(*location);                                            //  capitalize
      *country = toupper(*country);
      zdialog_stuff(zd,"location",location);
      zdialog_stuff(zd,"country",country);

      if (*lati > ' ' && ! strmatch(lati,"null") &&                              //  if coordinates present, validate
          *longi > ' ' && ! strmatch(longi,"null")) {
         err = validate_latlong(lati,longi,flati,flongi);
         if (err) goto badcoord;
      }

      if (! GScount) goto nofiles;

      if (*location <= ' ' || *country <= ' ' || *lati <= ' ' || *longi <= ' ') {
         yn = zmessageYN(Mwin,E2X("data is incomplete \n proceed?"));
         if (! yn) return 1;
      }

      put_geolocs(zd);                                                           //  update geolocs table

      zd->zstat = 3;                                                             //  OK to proceed
      zdialog_destroy(zd);
   }

   else zdialog_destroy(zd);                                                     //  [cancel] or [x]
   return 1;

badcoord:
   zmessageACK(Mwin,E2X("bad latitude/longitude: %s %s"),lati,longi);
   return 1;

nofiles:
   zmessageACK(Mwin,Bnofileselected);
   return 1;
}


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

//  Group images by location and date, with a count of images in each group.
//  Click on a group to get a thumbnail gallery of all images in the group.

namespace locs_names
{
   struct grec_t  {                                                              //  image geotags data
      char        *location, *country;                                           //  group location
      char        pdate[12];                                                     //  nominal group date, yyyymmdd
      int         lodate, hidate;                                                //  range, days since 0 CE
      int         count;                                                         //  images in group
   };

   grec_t   *grec = 0;
   int      Ngrec = 0;
   int      locs_groupby, locs_daterange;
   int      pline;

   int   locs_comp(cchar *rec1, cchar *rec2);
   int   locs_comp2(cchar *rec1, cchar *rec2);
   void  locs_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   locs_getdays(cchar *date);
}


//  menu function

void m_meta_places_dates(GtkWidget *, cchar *)
{
   using namespace locs_names;

   zdialog        *zd;
   int            zstat, ii, cc, cc1, cc2;
   int            yn, ww, iix, iig, newgroup;
   char           country[100], location[100], pdate[12];
   xxrec_t        *xxrec;
   GtkWidget      *textwin;

   F1_help_topic = "places_dates";

   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return;
   }
   
   if (Findexvalid == 1) zmessage_post_bold(Mwin,"20/10",2,Boldindex);           //  warn, index missing new files

   if (checkpend("all")) return;                                                 //  check nothing pending

/***
            Report Image Locations

         (o) Group by country
         (o) Group by country/location
         (o) Group by country/location/date
         (o) Group by date/country/location
             Combine within [ xx |-|+] days

                        [proceed]  [cancel]
***/

   zd = zdialog_new(E2X("Report Image Locations"),Mwin,Bproceed,Bcancel,null);
   zdialog_add_widget(zd,"radio","country","dialog",E2X("Group by country"));
   zdialog_add_widget(zd,"radio","location","dialog",E2X("Group by country/location"));
   zdialog_add_widget(zd,"radio","date","dialog",E2X("Group by country/location/date"));
   zdialog_add_widget(zd,"radio","date2","dialog",E2X("Group by date/country/location"));
   zdialog_add_widget(zd,"hbox","hbr","dialog");
   zdialog_add_widget(zd,"label","space","hbr",0,"space=10");
   zdialog_add_widget(zd,"label","labr1","hbr",E2X("Combine within"),"space=10");
   zdialog_add_widget(zd,"zspin","range","hbr","0|999|1|1");
   zdialog_add_widget(zd,"label","labr2","hbr",E2X("days"),"space=10");

   zdialog_stuff(zd,"country",0);
   zdialog_stuff(zd,"location",1);                                               //  default by location
   zdialog_stuff(zd,"date",0);
   zdialog_stuff(zd,"date2",0);
   
   zdialog_restore_inputs(zd);                                                   //  18.01
   zdialog_resize(zd,300,0);
   zdialog_run(zd,null,"parent");
   zstat = zdialog_wait(zd);
   if (zstat != 1) {
      zdialog_free(zd);
      return;
   }

   zdialog_fetch(zd,"country",iix);
   if (iix) locs_groupby = 1;                                                    //  group country
   zdialog_fetch(zd,"location",iix);
   if (iix) locs_groupby = 2;                                                    //  group country/location
   zdialog_fetch(zd,"date",iix);
   if (iix) locs_groupby = 3;                                                    //  group country/location/date-range
   zdialog_fetch(zd,"date2",iix);
   if (iix) locs_groupby = 4;                                                    //  group date-range/country/location
   
   zdialog_fetch(zd,"range",locs_daterange);                                     //  combine recs within date range

   zdialog_free(zd);

   if (Ngrec) {                                                                  //  free prior memory
      for (iix = 0; iix < Ngrec; iix++) {
         if (grec[iix].location) zfree(grec[iix].location);
         if (grec[iix].country) zfree(grec[iix].country);
      }
      zfree(grec);
   }

   cc = Nxxrec * sizeof(grec_t);                                                 //  allocate memory
   grec = (grec_t *) zmalloc(cc);
   memset(grec,0,cc);

   if (! Nxxrec) {
      zmessageACK(Mwin,"no geotags data found");
      return;
   }

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      xxrec = xxrec_tab[ii];

      grec[ii].location = zstrdup(xxrec->location);                              //  get location and country
      grec[ii].country = zstrdup(xxrec->country);

      strncpy0(grec[ii].pdate,xxrec->pdate,9);                                   //  photo date, truncate to yyyymmdd
      grec[ii].lodate = locs_getdays(xxrec->pdate);                              //  days since 0 CE
      grec[ii].hidate = grec[ii].lodate;
   }

   Ngrec = Nxxrec;

   if (Ngrec > 1)                                                                //  sort grecs by country/location/date
      HeapSort((char *) grec, sizeof(grec_t), Ngrec, locs_comp);

   iig = 0;                                                                      //  1st group from grec[0]
   grec[iig].count = 1;                                                          //  group count = 1

   for (iix = 1; iix < Ngrec; iix++)                                             //  scan following grecs
   {
      newgroup = 0;

      if (! strmatch(grec[iix].country,grec[iig].country))
         newgroup = 1;                                                           //  new country >> new group

      if (locs_groupby >= 2)                                                     //  new location >> new group 
         if (! strmatch(grec[iix].location,grec[iig].location)) newgroup = 1;    //    if group by location

      if (locs_groupby >= 3)
         if (grec[iix].lodate - grec[iig].hidate > locs_daterange)               //  new date >> new group if group by date
            newgroup = 1;                                                        //    and date out of range

      if (newgroup)
      {
         iig++;                                                                  //  new group
         if (iix > iig) {
            grec[iig] = grec[iix];                                               //  copy and pack down
            grec[iix].location = grec[iix].country = 0;                          //  no zfree()
         }
         grec[iig].count = 1;                                                    //  group count = 1
      }
      else
      {
         zfree(grec[iix].location);                                              //  same group
         zfree(grec[iix].country);                                               //  free memory
         grec[iix].location = grec[iix].country = 0;
         grec[iig].hidate = grec[iix].lodate;                                    //  expand group date-range
         grec[iig].count++;                                                      //  increment group count
      }
   }

   Ngrec = iig + 1;                                                              //  unique groups count

   if (locs_groupby == 1) ww = 350;                                              //  group country
   if (locs_groupby == 2) ww = 600;                                              //  group country/location
   if (locs_groupby == 3) ww = 650;                                              //  group country/location/date-range
   if (locs_groupby == 4) ww = 650;                                              //  group date-range/country/location

   textwin = popup_report_open(Mwin,E2X("Image Locations"),ww,400);              //  write groups to popup window

   if (locs_groupby == 1)                                                        //  group by country
   {
      popup_report_header(1,"%-30s  %5s","Country","Count");

      for (iig = 0; iig < Ngrec; iig++)
      {
         utf8substring(country,grec[iig].country,0,30);
         cc1 = 30 + strlen(country) - utf8len(country);
         popup_report_write(0,"%-*s  %5d \n",cc1,country,grec[iig].count);
      }
   }

   if (locs_groupby == 2)                                                        //  group by country/location
   {
      popup_report_header(1,"%-30s  %-30s  %5s","Country","Location","Count");

      for (iig = 0; iig < Ngrec; iig++)
      {
         utf8substring(country,grec[iig].country,0,30);
         cc1 = 30 + strlen(country) - utf8len(country);
         utf8substring(location,grec[iig].location,0,30);
         cc2 = 30 + strlen(location) - utf8len(location);
         popup_report_write(0,"%-*s  %-*s  %5d \n",cc1,country,cc2,location,grec[iig].count);
      }
   }

   if (locs_groupby == 3)                                                        //  group by country/location/date-range
   {
      popup_report_header(1,"%-26s  %-26s  %-10s   %5s","Country","Location","Date","Count");

      for (iig = 0; iig < Ngrec; iig++)
      {
         utf8substring(country,grec[iig].country,0,26);                          //  get graphic cc for UTF-8 names
         cc1 = 26 + strlen(country) - utf8len(country);
         utf8substring(location,grec[iig].location,0,26);
         cc2 = 26 + strlen(location) - utf8len(location);

         strncpy(pdate,grec[iig].pdate,8);                                       //  date, yyyymmdd
         if (! strmatch(pdate,"null")) {
            memmove(pdate+8,pdate+6,2);                                          //  convert to yyyy-mm-dd
            memmove(pdate+5,pdate+4,2);
            pdate[4] = pdate[7] = '-';
            pdate[10] = 0;
         }

         popup_report_write(0,"%-*s  %-*s  %-10s  %6d \n",cc1,country,cc2,location,pdate,grec[iig].count);
      }
   }

   if (locs_groupby == 4)                                                        //  group by date-range/country/location
   {
      if (Ngrec > 1)                                                             //  re-sort by date/country/location
         HeapSort((char *) grec, sizeof(grec_t), Ngrec, locs_comp2);
   
      popup_report_header(1,"%-10s  %-26s  %-26s   %5s","Date","Country","Location","Count");

      for (iig = 0; iig < Ngrec; iig++)
      {
         utf8substring(country,grec[iig].country,0,26);                          //  get graphic cc for UTF-8 names
         cc1 = 26 + strlen(country) - utf8len(country);
         utf8substring(location,grec[iig].location,0,26);
         cc2 = 26 + strlen(location) - utf8len(location);

         strncpy(pdate,grec[iig].pdate,8);                                       //  date, yyyymmdd
         if (! strmatch(pdate,"null")) {
            memmove(pdate+8,pdate+6,2);                                          //  convert to yyyy-mm-dd
            memmove(pdate+5,pdate+4,2);
            pdate[4] = pdate[7] = '-';
            pdate[10] = 0;
         }

         popup_report_write(0,"%-10s  %-*s  %-*s  %6d \n",pdate,cc1,country,cc2,location,grec[iig].count);
      }
   }

   textwidget_set_callbackfunc(textwin,locs_clickfunc);                          //  response function for mouse click
   pline = 0;
   return;
}


//  Compare 2 grec records by geotags and date,
//  return < 0  = 0  > 0   for   rec1  <  =  >  rec2.

int locs_names::locs_comp(cchar *rec1, cchar *rec2)
{
   using namespace locs_names;

   int      ii;

   char * country1 = ((grec_t *) rec1)->country;                                 //  compare countries
   char * country2 = ((grec_t *) rec2)->country;
   ii = strcmp(country1,country2);
   if (ii) return ii;

   char * loc1 = ((grec_t *) rec1)->location;                                    //  compare cities
   char * loc2 = ((grec_t *) rec2)->location;
   ii = strcmp(loc1,loc2);
   if (ii) return ii;

   int date1 = ((grec_t *) rec1)->lodate;                                        //  compare dates
   int date2 = ((grec_t *) rec2)->lodate;
   ii = date1 - date2;
   return ii;
}


//  Compare 2 grec records by date and geotags,
//  return < 0  = 0  > 0   for   rec1  <  =  >  rec2.

int locs_names::locs_comp2(cchar *rec1, cchar *rec2)
{
   using namespace locs_names;

   int      ii;

   int date1 = ((grec_t *) rec1)->lodate;                                        //  compare dates
   int date2 = ((grec_t *) rec2)->lodate;
   ii = date1 - date2;
   if (ii) return ii;

   char * country1 = ((grec_t *) rec1)->country;                                 //  compare countries
   char * country2 = ((grec_t *) rec2)->country;
   ii = strcmp(country1,country2);
   if (ii) return ii;

   char * loc1 = ((grec_t *) rec1)->location;                                    //  compare cities
   char * loc2 = ((grec_t *) rec2)->location;
   ii = strcmp(loc1,loc2);
   return ii;
}


//  convert yyyymmdd date into days from 0 C.E.
//  "null" date returns 999999 (year 2737)

int locs_names::locs_getdays(cchar *date)
{
   using namespace locs_names;

   int      year, month, day;
   char     temp[8];
   int      montab[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
   int      elaps;

   year = month = day = 0;

   strncpy0(temp,date,5);
   year = atoi(temp);

   strncpy0(temp,date+4,3);
   month = atoi(temp);

   strncpy0(temp,date+6,3);
   day = atoi(temp);

   elaps = 365 * (year-1) + (year-1) / 4;                                        //  elapsed days in prior years
   elaps += montab[month-1];                                                     //  + elapsed days in prior months
   if (year % 4 == 0 && month > 2) elaps += 1;                                   //  + 1 for Feb. 29
   elaps += day-1;                                                               //  + elapsed days in month
   return elaps;
}


//  Receive clicks on report window and generate gallery of images
//  matching the selected country/location/date

void locs_names::locs_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace locs_names;

   int            ii, cc, nn;
   int            lodate, hidate, datex;
   static char    matchtext[20];
   char           location[100], country[100];
   FILE           *fid;
   xxrec_t        *xxrec;
   
   if (checkpend("all")) return;                                                 //  check nothing pending
   
   if (line >= 0)                                                                //  line clicked
   {
      textwidget_scroll(widget,line);                                            //  keep line on screen                18.01
      textwidget_highlight_line(widget,line);                                    //  highlight
      pline = line;                                                              //  remember last line selected
      *matchtext = 0;
   }
   
   else                                                                          //  KBkey pressed
   {
      if (kbkey == GDK_KEY_F1) {                                                 //  key F1 pressed, show help          18.01
         showz_userguide(F1_help_topic);
         *matchtext = 0;
         return;
      }

      if (kbkey >= 0xfd00) {
         if (kbkey == GDK_KEY_Up) pline--;                                       //  KB arrow key navigation
         if (kbkey == GDK_KEY_Down) pline++;
         if (kbkey == GDK_KEY_Page_Up) pline -= 10;
         if (kbkey == GDK_KEY_Page_Down) pline += 10;
         if (kbkey == GDK_KEY_Home) pline = 0;
         if (kbkey == GDK_KEY_End) pline = Ngrec - 1;
         if (pline < 0) pline = 0;
         if (pline > Ngrec-1) pline = Ngrec - 1;
         textwidget_highlight_line(widget,pline);                                //  highlight line
         *matchtext = 0;
      }
      
      else {                                                                     //  other keys - look for matching text
         cc = strlen(matchtext);
         if (cc >= 19) return;
         matchtext[cc] = kbkey;
         matchtext[cc+1] = 0;
         nn = textwidget_find(widget,matchtext,pline);                           //  highlight matching text
         if (nn >= 0) pline = nn;
      }
   }

   textwidget_scroll(widget,pline);                                              //  keep line on screen                18.01

   strncpy0(country,grec[pline].country,99);                                     //  selected country/location/date-range
   strncpy0(location,grec[pline].location,99);
   lodate = grec[pline].lodate;
   hidate = grec[pline].hidate;

   fid = fopen(searchresults_file,"w");                                          //  open output file
   if (! fid) goto filerror;

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];

      if (! strmatch(xxrec->country,country)) continue;                          //  no country match
      
      if (locs_groupby >= 2)
         if (! strmatch(xxrec->location,location)) continue;                     //  no location match 

      if (locs_groupby >= 3) { 
         datex = locs_getdays(xxrec->pdate);
         if (datex < lodate || datex > hidate) continue;                         //  no date match
      }

      fprintf(fid,"%s\n",xxrec->file);                                           //  output matching file
   }

   fclose(fid);

   free_resources();
   navi::gallerytype = SEARCH;                                                   //  search results
   gallery(searchresults_file,"initF",0);                                        //  generate gallery of matching files
   gallery(0,"paint",0);
   m_viewmode(0,"G");
   return;

filerror:
   zmessageACK(Mwin,"file error: %s",strerror(errno));
   return;
}


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

//  Produce a report of image counts by year and month.
//  Click on a report line to get a thumbnail gallery of images.

namespace timeline_names
{
   int      Nyears = 2100;
   int      Nperds = 12 * Nyears;
   int      Nyears2 = 0;
   cchar    *months = E2X("Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec");
   int      colpos[14] = { 0, 6, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58, 63, 68 };
}


//  menu function

void m_meta_timeline(GtkWidget *, cchar *)
{
   using namespace timeline_names;

   void  timeline_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);

   int         Ycount[Nyears], Pcount[Nperds];                                   //  image counts per year and period
   int         Ncount, Ecount;                                                   //  counts for "null" and invalid dates
   int         yn, ii, jj, cc;
   int         yy, mm, pp;
   char        pdate[8], nnnnn[8], buff[100];
   xxrec_t     *xxrec;
   GtkWidget   *textwin;

   F1_help_topic = "image_timeline";
   
   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return;
   }
   
   if (Findexvalid == 1) zmessage_post_bold(Mwin,"20/10",2,Boldindex);           //  warn, index missing new files

   if (checkpend("all")) return;                                                 //  check nothing pending

   Ncount = Ecount = 0;                                                          //  clear null and error counts

   for (yy = 0; yy < Nyears; yy++)                                               //  clear totals per year
      Ycount[yy] = 0;
   
   for (pp = 0; pp < Nperds; pp++)                                               //  clear totals per period (month)
      Pcount[pp] = 0;

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];

      strncpy0(pdate,xxrec->pdate,7);                                            //  photo date, truncate to yyyymm

      if (strmatch(pdate,"null")) {                                              //  if null, add to null count
         ++Ncount;
         continue;
      }
      
      jj = atoi(pdate);                                                          //  photo date, 0 to 209912
      yy = jj / 100;                                                             //  year, 0000 to 2099
      mm = jj - yy * 100;                                                        //  month, 1 to 12
      if (yy < 0 || yy >= Nyears || mm < 1 || mm > 12) {
         ++Ecount;                                                               //  invalid, add to error count
         continue;
      }
     
      ++Ycount[yy];                                                              //  add to year totals
      pp = yy * 12 + mm - 1;                                                     //  add to period totals
      ++Pcount[pp];
   }

   textwin = popup_report_open(Mwin,"Image Timeline",600,400);                   //  write report to popup window
   popup_report_header(1,"year  count  %s",months);                              //  "year   count  Jan  Feb  ... "
   
   if (Ncount) 
      popup_report_write(0,"null  %-6d \n",Ncount);                              //  images with no date
   
   if (Ecount) 
      popup_report_write(0,"invalid %-4d \n",Ecount);                            //  images with invalid date
   
   Nyears2 = 0;

   for (yy = 0; yy < Nyears; yy++)                                               //  loop years
   {
      if (! Ycount[yy]) continue;                                                //  omit years without images
      
      snprintf(buff,100,"%04d  %-6d ",yy,Ycount[yy]);                            //  output "yyyy  NNNNNN "
      cc = 13;

      for (mm = 0; mm < 12; mm++) {                                              //  loop months 0 - 11
         pp = yy * 12 + mm;                                                      //  period
         snprintf(nnnnn,6,"%-5d",Pcount[pp]);                                    //  output "NNNNN" 
         strncpy(buff+cc,nnnnn,5);
         cc += 5;
      }

      buff[cc] = 0;
      popup_report_write(0,"%s \n",buff);

      Nyears2++;                                                                 //  count reported years
   }

   popup_report_bottom();                                                        //  18.07

   textwidget_set_callbackfunc(textwin,timeline_clickfunc);                      //  response function for mouse click
   return;
}


//  Receive clicks on report window and generate gallery of images
//  matching the selected period

void timeline_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace timeline_names;

   int         ii, jj, cc;
   int         Fnull = 0, Finvalid = 0;
   int         yy, mm;
   static int  pline, ppos;
   char        *txline, pdate[8], *pp, end;
   FILE        *fid;
   xxrec_t     *xxrec;

   if (checkpend("all")) return;                                                 //  check nothing pending
   
   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }
   
   if (line == -1)                                                               //  arrow key navigation               18.01
   {
      for (ii = 0; ii < 14; ii++)                                                //  current report column
         if (ppos == colpos[ii]) break;

      if (kbkey == GDK_KEY_Left) {                                               //  prior month
         if (ii > 2) ppos = colpos[ii-1];
         else { 
            pline -= 1;
            ppos = colpos[13]; 
         }
      }

      else if (kbkey == GDK_KEY_Right) {                                         //  next month
         if (ii < 13) ppos = colpos[ii+1];
         else {
            pline += 1;
            ppos = colpos[2];
         }
      }

      else if (kbkey == GDK_KEY_Up) pline -= 1;                                  //  prior year
      else if (kbkey == GDK_KEY_Down) pline += 1;                                //  next year

      line = pline;
      pos = ppos;
   }
   
   if (line < 0) line = 0;
   if (line > Nyears2) line = Nyears2;                                           //  18.01
   if (pos < 0) pos = 0;

   for (ii = 0; ii < 14; ii++)
      if (pos < colpos[ii]) break;
   pos = colpos[ii-1];

   textwidget_scroll(widget,line);                                               //  keep line on screen

   pline = line;                                                                 //  remember chosen line, position     18.01
   ppos = pos;

   pp = textwidget_word(widget,line,pos," ",end);                                //  hilite clicked word
   if (pp) textwidget_highlight_word(widget,line,pos,strlen(pp));

   txline = textwidget_line(widget,line,1);                                      //  get clicked line
   if (! txline || ! *txline) return;

   cc = 0;

   if (strmatchN(txline,"null",4)) Fnull = 1;                                    //  find images with null date

   else if (strmatchN(txline,"invalid",7)) Finvalid = 1;                         //  find images with invalid date

   else if (pos < 13) {                                                          //  clicked on year or year count
      strncpy0(pdate,txline,5);                                                  //  have "yyyy"
      cc = 4;
   }
   
   else                                                                          //  month was clicked
   {
      mm = (pos - 13) / 5 + 1;                                                   //  month, 1-12
      if (mm < 1 || mm > 12) return;
      strncpy(pdate,txline,4);                                                   //  "yyyy"
      pdate[4] = '0' + mm/10;
      pdate[5] = '0' + mm % 10;                                                  //  have "yyyymm"
      pdate[6] = 0;
      cc = 6;
   }

   fid = fopen(searchresults_file,"w");                                          //  open output file
   if (! fid) goto filerror;

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];
      
      if (Fnull) {                                                               //  search for missing dates
         if (strmatch(xxrec->pdate,"null")) {
            fprintf(fid,"%s\n",xxrec->file);
            continue;
         }
      }
      
      else if (Finvalid) {                                                       //  search for invalid dates
         if (strmatch(xxrec->pdate,"null")) continue;                            //  reject "null" 
         strncpy0(pdate,xxrec->pdate,7);                                         //  yyyymm
         jj = atoi(pdate);                                                       //  0 to 209912
         yy = jj / 100;                                                          //  0 to 2099
         mm = jj - yy * 100;                                                     //  1 to 12
         if (yy < 0 || yy >= Nyears || mm < 1 || mm > 12) {
            fprintf(fid,"%s\n",xxrec->file);
            continue;
         }
      }            

      else if (strmatchN(xxrec->pdate,pdate,cc)) {                               //  screen for desired period
         if (strmatch(xxrec->pdate,"null")) continue;                            //  reject "null"
         strncpy0(pdate,xxrec->pdate,7);                                         //  yyyymm
         jj = atoi(pdate);                                                       //  0 to 209912
         yy = jj / 100;                                                          //  0 to 2099
         mm = jj - yy * 100;                                                     //  1 to 12
         if (yy < 0 || yy >= Nyears || mm < 1 || mm > 12) continue;              //  invalid, reject
         fprintf(fid,"%s\n",xxrec->file);                                        //  output matching file
      }
   }

   fclose(fid);

   free_resources();
   navi::gallerytype = SEARCH;                                                   //  search results
   gallery(searchresults_file,"initF",0);                                        //  generate gallery of matching files
   gallery(0,"paint",0);
   m_viewmode(0,"G");
   return;

filerror:
   zmessageACK(Mwin,"file error: %s",strerror(errno));
   return;
}


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

//  Search image tags, geotags, dates, stars, comments, captions
//  to find matching images. This is fast using the image index.
//  Search also any other metadata, but relatively slow.

namespace search_images
{
   zdialog  *zdsearchimages = 0;                                                 //  search images dialog

   char     searchDateFrom[20] = "";                                             //  search images
   char     searchDateTo[20] = "";                                               //  format is "yyyy-mm-dd hh:mm"       18.01
   char     searchdatelo[16], searchdatehi[16];                                  //  format is yyyymmddhhmmss           18.01

   char     searchStarsFrom[4] = "";
   char     searchStarsTo[4] = "";

   char     searchtags[tagScc] = "";                                             //  search tags list
   char     searchtext[tagScc] = "";                                             //  search comments & captions word list
   char     searchfiles[tagScc] = "";                                            //  search files list

   char     searchLocations[200] = "";                                           //  search locations

   int      Fscanall, Fscancurr, Fnewset, Faddset, Fremset;
   int      Ftext, Ffiles, Ftags, Fstars, Flocs;
   int      Fdates, Fphotodate, Ffiledate, Fnulldate;
   int      Flastver, Fallvers, Fmeta;
   int      Falltags, Falltext, Fallfiles, Falllocs;
   int      Frepgallery, Frepmeta;

   int      Nsearchkeys = 0;
   char     *searchkeys[5];                                                      //  metadata keys to search
   char     *searchvals[5];                                                      //  data values to search for
   char     matchtype[5];                                                        //  match type: string or number < = >
   int      keyindexed[5];                                                       //  key included in indexed metadata
   int      allkeysindexed;                                                      //  all search keys are indexed
}

using namespace search_images;


//  menu function

void m_search_images(GtkWidget *, cchar *)
{
   void  search_searchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  search_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   void  search_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey);
   int   searchimages_dialog_event(zdialog*, cchar *event);

   int         yn;
   zdialog     *zd;
   GtkWidget   *widget;

   F1_help_topic = "search_images";

   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return;
   }
   
   if (Findexvalid == 1) zmessage_post_bold(Mwin,"20/10",2,Boldindex);           //  warn, index missing new files

   if (checkpend("all")) return;                                                 //  check nothing pending

/***
          ______________________________________________________________
         |                   Search Images                              |
         |                                                              |
         |  images to search: (o) all  (o) current set only             |
         |  matching images: (o) new set  (o) add to set  (o) remove    |
         |  [x] last version only  [x] all versions of matching images  |
         |  report type: (o) gallery  (o) metadata                      |
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  date range   [______________] [______________]              |
         |   (o) photo date  (o) file date   yyyy-mm-dd                 |
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  stars range  [__] [__]                                      |
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |                                                     all/any  |
         |  search tags  [___________________________________] (o) (o)  |
         |  search text  [___________________________________] (o) (o)  |
         |  search files [___________________________________] (o) (o)  |
         |  search locations [_______________________________] (o) (o)  |        //  17.08
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  search metadata [Add] (*)                                   |
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  Enter Search Tag [________________________]                 |
         |  Matching Tags [__________________________________________]  |
         |   - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  |
         |  Defined Tags Category [_________________________________|v] |
         |  |                                                         | |
         |  |                                                         | |
         |  |                                                         | |
         |  |                                                         | |
         |  |                                                         | |
         |  |                                                         | |
         |  |_________________________________________________________| |
         |                                                              |
         |                                   [clear] [proceed] [cancel] |
         |______________________________________________________________|

***/

   zd = zdialog_new(E2X("Search Images"),Mwin,Bclear,Bproceed,Bcancel,null);
   zdsearchimages = zd;

   zdialog_add_widget(zd,"hbox","hbs1","dialog");
   zdialog_add_widget(zd,"label","labs1","hbs1",E2X("images to search:"),"space=3");
   zdialog_add_widget(zd,"radio","allimages","hbs1",E2X("all"),"space=3");
   zdialog_add_widget(zd,"radio","currset","hbs1",E2X("current set only"),"space=3");

   zdialog_add_widget(zd,"hbox","hbm1","dialog");
   zdialog_add_widget(zd,"label","labs1","hbm1",E2X("matching images:"),"space=3");
   zdialog_add_widget(zd,"radio","newset","hbm1",E2X("new set"),"space=5");
   zdialog_add_widget(zd,"radio","addset","hbm1",E2X("add to set"),"space=5");
   zdialog_add_widget(zd,"radio","remset","hbm1",E2X("remove"),"space=5");

   zdialog_add_widget(zd,"hbox","hbver","dialog");
   zdialog_add_widget(zd,"check","lastver","hbver",E2X("last version only"),"space=3");
   zdialog_add_widget(zd,"check","allvers","hbver",E2X("all versions of matching images"),"space=10");

   zdialog_add_widget(zd,"hbox","hbrt","dialog");
   zdialog_add_widget(zd,"label","labrt","hbrt",E2X("report type:"),"space=3");
   zdialog_add_widget(zd,"radio","repgallery","hbrt",E2X("gallery"),"space=5");
   zdialog_add_widget(zd,"radio","repmeta","hbrt","Metadata","space=5");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=2");

   zdialog_add_widget(zd,"hbox","hbd1","dialog");
   zdialog_add_widget(zd,"label","labD","hbd1",E2X("date range"),"space=3");
   zdialog_add_widget(zd,"zentry","datefrom","hbd1",0,"size=12|space=5");
   zdialog_add_widget(zd,"zentry","dateto","hbd1",0,"size=12");
   
   zdialog_add_widget(zd,"hbox","hbd2","dialog");                                //  18.01
   zdialog_add_widget(zd,"radio","photodate","hbd2",E2X("photo date"),"space=8");
   zdialog_add_widget(zd,"radio","filedate","hbd2",E2X("file date"));
   zdialog_add_widget(zd,"label","labD","hbd2",E2X("(yyyy-mm-dd)"),"space=20");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=2");

   zdialog_add_widget(zd,"hbox","hbstars","dialog");
   zdialog_add_widget(zd,"label","labS","hbstars",E2X("stars range"),"space=3");
   zdialog_add_widget(zd,"zentry","starsfrom","hbstars",0,"size=2|space=3");
   zdialog_add_widget(zd,"zentry","starsto","hbstars",0,"size=2|space=5");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=2");

   zdialog_add_widget(zd,"hbox","hbaa","dialog");
   zdialog_add_widget(zd,"label","space","hbaa",0,"expand");
   zdialog_add_widget(zd,"label","all-any","hbaa",E2X("all/any"));

   zdialog_add_widget(zd,"hbox","hbtags","dialog","space=1");
   zdialog_add_widget(zd,"label","labtags","hbtags",E2X("search tags"),"space=3");
   zdialog_add_widget(zd,"frame","frtags","hbtags",0,"expand");
   zdialog_add_widget(zd,"text","searchtags","frtags",0,"expand|wrap");
   zdialog_add_widget(zd,"radio","alltags","hbtags",0,"space=3");
   zdialog_add_widget(zd,"radio","anytags","hbtags",0,"space=5");

   zdialog_add_widget(zd,"hbox","hbtext","dialog","space=1");
   zdialog_add_widget(zd,"label","labtext","hbtext",E2X("search text"),"space=3");
   zdialog_add_widget(zd,"zentry","searchtext","hbtext",0,"expand");
   zdialog_add_widget(zd,"radio","alltext","hbtext",0,"space=3");
   zdialog_add_widget(zd,"radio","anytext","hbtext",0,"space=5");

   zdialog_add_widget(zd,"hbox","hbfiles","dialog","space=1");
   zdialog_add_widget(zd,"label","labfiles","hbfiles",E2X("search files"),"space=3");
   zdialog_add_widget(zd,"zentry","searchfiles","hbfiles",0,"expand");
   zdialog_add_widget(zd,"radio","allfiles","hbfiles",0,"space=3");
   zdialog_add_widget(zd,"radio","anyfiles","hbfiles",0,"space=5");

   zdialog_add_widget(zd,"hbox","hblocs","dialog","space=1");
   zdialog_add_widget(zd,"label","lablocs","hblocs",E2X("search locations"),"space=3");
   zdialog_add_widget(zd,"zentry","searchlocs","hblocs",0,"expand");
   zdialog_add_widget(zd,"radio","alllocs","hblocs",0,"space=3");                //  17.08
   zdialog_add_widget(zd,"radio","anylocs","hblocs",0,"space=5");
   zdialog_add_ttip(zd,"searchlocs",E2X("enter cities, countries")); 

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=2");

   zdialog_add_widget(zd,"hbox","hbmeta","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labmeta","hbmeta",E2X("search other metadata"),"space=3");
   zdialog_add_widget(zd,"button","addmeta","hbmeta",Badd,"space=8");
   zdialog_add_widget(zd,"label","metadata#","hbmeta","(  )");
   
   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=2");

   zdialog_add_widget(zd,"hbox","hbnt","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labnt","hbnt",E2X("Enter Search Tag"),"space=3");
   zdialog_add_widget(zd,"zentry","entertag","hbnt",0,"size=20");

   zdialog_add_widget(zd,"hbox","hbmt","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labmt","hbmt",E2X("Matching Tags"),"space=3");
   zdialog_add_widget(zd,"frame","frmt","hbmt",0,"expand");
   zdialog_add_widget(zd,"text","matchtags","frmt",0,"wrap|expand");

   zdialog_add_widget(zd,"hsep","sep","dialog",0,"space=3");

   zdialog_add_widget(zd,"hbox","hbdt1","dialog");
   zdialog_add_widget(zd,"label","labdt","hbdt1",E2X("Defined Tags Category"),"space=3");
   zdialog_add_widget(zd,"label","space","hbdt1",0,"expand");
   zdialog_add_widget(zd,"combo","defcats","hbdt1",0,"expand|space=5");

   zdialog_add_widget(zd,"hbox","hbdt2","dialog",0,"expand");
   zdialog_add_widget(zd,"frame","frdt2","hbdt2",0,"expand|space=3");
   zdialog_add_widget(zd,"scrwin","swdt2","frdt2",0,"expand");
   zdialog_add_widget(zd,"text","deftags","swdt2",0,"wrap");

   widget = zdialog_widget(zd,"searchtags");                                     //  tag widget mouse functions
   textwidget_set_callbackfunc(widget,search_searchtags_clickfunc);

   widget = zdialog_widget(zd,"matchtags");
   textwidget_set_callbackfunc(widget,search_matchtags_clickfunc);

   widget = zdialog_widget(zd,"deftags");
   textwidget_set_callbackfunc(widget,search_deftags_clickfunc);
   
   zdialog_stuff(zd,"allimages",1);                                              //  defaults
   zdialog_stuff(zd,"currset",0);
   zdialog_stuff(zd,"newset",1);
   zdialog_stuff(zd,"addset",0);
   zdialog_stuff(zd,"remset",0);
   zdialog_stuff(zd,"repgallery",1);
   zdialog_stuff(zd,"repmeta",0);
   zdialog_stuff(zd,"photodate",1);                                              //  18.07
   zdialog_stuff(zd,"filedate",0);
   zdialog_stuff(zd,"lastver",0);
   zdialog_stuff(zd,"allvers",0);                                                //  18.07
   zdialog_stuff(zd,"alltags",0);
   zdialog_stuff(zd,"anytags",1);
   zdialog_stuff(zd,"alltext",0);
   zdialog_stuff(zd,"anytext",1);
   zdialog_stuff(zd,"allfiles",0);
   zdialog_stuff(zd,"anyfiles",1);
   zdialog_stuff(zd,"alllocs",0);                                                //  17.08
   zdialog_stuff(zd,"anylocs",1);

   zdialog_restore_inputs(zd);                                                   //  preload prior user inputs
   
   load_deftags();                                                               //  stuff defined tags into dialog
   deftags_stuff(zd,"ALL");
   defcats_stuff(zd);                                                            //  and defined categories

   zdialog_resize(zd,0,700);                                                     //  start dialog
   zdialog_run(zd,searchimages_dialog_event,"50/10");
   zdialog_wait(zd);                                                             //  wait for dialog completion
   zdialog_free(zd);

   return;
}


//  search tag was clicked

void search_searchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;:",end);
   if (! txtag) return;

   del_tag(txtag,searchtags);                                                    //  remove from search list
   zdialog_stuff(zdsearchimages,"searchtags",searchtags);

   zfree(txtag);
   return;
}


//  matching tag was clicked 

void search_matchtags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey) 
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;",end);
   if (! txtag) return;

   add_tag(txtag,searchtags,tagScc);                                             //  add to search tag list

   zdialog_stuff(zdsearchimages,"entertag","");                                  //  update dialog widgets
   zdialog_stuff(zdsearchimages,"matchtags","");
   zdialog_stuff(zdsearchimages,"searchtags",searchtags);

   zdialog_goto(zdsearchimages,"entertag");                                      //  focus back to entertag widget

   zfree(txtag);
   return;
}


//  defined tag was clicked

void search_deftags_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   char     *txtag, end = 0;

   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   txtag = textwidget_word(widget,line,pos,",;:",end);
   if (! txtag || end == ':') return;                                            //  tag category clicked, ignore

   add_tag(txtag,searchtags,tagScc);                                             //  add to search tag list
   zdialog_stuff(zdsearchimages,"searchtags",searchtags);

   zfree(txtag);
   return;
}


//  search images dialog event and completion callback function

int searchimages_dialog_event(zdialog *zd, cchar *event)                         //  overhauled
{
   using namespace navi;

   int  datetimeOK(char *datetime);
   int  searchimages_select(xxrec_t *xxrec);
   int  searchimages_metadata_dialog(zdialog *zd);
   int  searchimages_metadata_report();

   cchar    dateLoDefault[20] = "0000-01-01 00:00:00";                           //  start of time                      18.01
   cchar    dateHiDefault[20] = "2099-12-31 23:59:59";                           //  end of fime

   char     *file, *filever;
   char     **flist, *pp, buffer[XFCC];
   char     mm[4] = "mm";
   int      match, ii, jj, err, cc;
   int      nt, cc1, cc2, ff, ftf;
   int      Nadded, Nremoved, Nleft, Npver;
   xxrec_t  *xxrec;
   FILE     *fid;
   char     *pp1, *pp2;
   char     entertag[tagcc], matchtags[20][tagcc];
   char     matchtagstext[(tagcc+2)*20];
   char     catgname[tagcc];
   char     albumfile[200];

   if (strmatch(event,"addmeta"))                                                //  get other metadata criteria
      Fmeta = searchimages_metadata_dialog(zd);

   if (Fmeta) zdialog_stuff(zd,"metadata#","(*)");                               //  show presense of metadata criteria
   else zdialog_stuff(zd,"metadata#","(_)");

   if (zd->zstat == 1)                                                           //  clear selection criteria 
   {
      zdialog_stuff(zd,"allimages",1);
      zdialog_stuff(zd,"currset",0);
      zdialog_stuff(zd,"newset",1);
      zdialog_stuff(zd,"addset",0);
      zdialog_stuff(zd,"remset",0);
      zdialog_stuff(zd,"repgallery",1);
      zdialog_stuff(zd,"repmeta",0);
      zdialog_stuff(zd,"lastver",0);
      zdialog_stuff(zd,"allvers",0);                                             //  18.07
      zdialog_stuff(zd,"alltags",0);
      zdialog_stuff(zd,"anytags",1);
      zdialog_stuff(zd,"alltext",0);
      zdialog_stuff(zd,"anytext",1);
      zdialog_stuff(zd,"allfiles",0);
      zdialog_stuff(zd,"anyfiles",1);
      zdialog_stuff(zd,"datefrom","");
      zdialog_stuff(zd,"dateto","");
      zdialog_stuff(zd,"photodate",1);                                           //  18.07
      zdialog_stuff(zd,"filedate",0);
      zdialog_stuff(zd,"starsfrom","");
      zdialog_stuff(zd,"starsto","");
      zdialog_stuff(zd,"searchtags","");
      zdialog_stuff(zd,"searchtext","");
      zdialog_stuff(zd,"searchfiles","");
      zdialog_stuff(zd,"searchlocs","");

      *searchtags = 0;

      Flocs = 0;
      *searchLocations = 0;

      zdialog_stuff(zd,"metadata#","( )");
      Fmeta = 0;
      Nsearchkeys = 0;

      zd->zstat = 0;                                                             //  keep dialog active
      return 1;
   }

   if (strmatch(event,"lastver")) {                                              //  if "last version" selected,        18.07
      zdialog_fetch(zd,"lastver",ii);                                            //     unselect "all versions"
      if (ii) zdialog_stuff(zd,"allvers",0);
   }

   if (strmatch(event,"allvers")) {                                              //  if "all versions" selected,        18.07
      zdialog_fetch(zd,"allvers",ii);                                            //     unselect "last version"
      if (ii) zdialog_stuff(zd,"lastver",0);
   }
   
   if (strmatch(event,"entertag"))                                               //  new tag is being typed in
   {
      zdialog_stuff(zd,"matchtags","");                                          //  clear matchtags in dialog

      zdialog_fetch(zd,"entertag",entertag,tagcc);                               //  get chars. typed so far
      cc1 = strlen(entertag);
      
      for (ii = jj = 0; ii <= cc1; ii++) {                                       //  remove foul characters
         if (strchr(",:;",entertag[ii])) continue;
         entertag[jj++] = entertag[ii];
      }
      
      if (jj < cc1) {                                                            //  something was removed
         entertag[jj] = 0;
         cc1 = jj;
         zdialog_stuff(zd,"entertag",entertag);
      }

      if (cc1 < 2) return 1;                                                     //  wait for at least 2 chars.

      for (ii = nt = 0; ii < maxtagcats; ii++)                                   //  loop all categories
      {
         pp2 = tags_deftags[ii];                                                 //  category: aaaaaa, bbbbb, ... tagN,
         if (! pp2) continue;                                                    //            |     |
         pp2 = strchr(pp2,':');                                                  //            pp1   pp2
         
         while (true)                                                            //  loop all deftags in category
         {
            pp1 = pp2 + 2;
            if (! *pp1) break;
            pp2 = strchr(pp1,',');
            if (! pp2) break;
            if (strmatchcaseN(entertag,pp1,cc1)) {                               //  deftag matches chars. typed so far
               cc2 = pp2 - pp1;
               strncpy(matchtags[nt],pp1,cc2);                                   //  save deftags that match
               matchtags[nt][cc2] = 0;
               if (++nt == 20) return 1;                                         //  quit if 20 matches or more
            }
         }
      }
      
      if (nt == 0) return 1;                                                     //  no matches

      pp1 = matchtagstext;

      for (ii = 0; ii < nt; ii++)                                                //  make deftag list: aaaaa, bbb, cccc ...
      {
         strcpy(pp1,matchtags[ii]);
         pp1 += strlen(pp1);
         strcpy(pp1,", ");
         pp1 += 2;
      }
      
      zdialog_stuff(zd,"matchtags",matchtagstext);                               //  stuff matchtags in dialog
      return 1;
   }

   if (strmatch(event,"defcats")) {                                              //  new tag category selection 
      zdialog_fetch(zd,"defcats",catgname,tagcc);
      deftags_stuff(zd,catgname);
   }
   
   if (zd->zstat != 2) return 1;                                                 //  cancel if not [proceed]

//  Inputs are complete. Validate all inputs. -----------------------------------

   zdialog_fetch(zd,"allimages",Fscanall);                                       //  search all images
   zdialog_fetch(zd,"currset",Fscancurr);                                        //  search current set (gallery)
   zdialog_fetch(zd,"newset",Fnewset);                                           //  matching images --> new set
   zdialog_fetch(zd,"addset",Faddset);                                           //  add matching image to set
   zdialog_fetch(zd,"remset",Fremset);                                           //  remove matching images from set

   if (Fremset && Fscanall) {                                                    //  illogical search
      zmessageACK(Mwin,E2X("to remove images from current set, \n"
                           "search current set"));
      zd->zstat = 0;                                                             //  keep dialog active
      return 1;
   }

   if (Faddset && Fscancurr) {
      zmessageACK(Mwin,E2X("to add images to current set, \n"
                           "search all images"));
      zd->zstat = 0;                                                             //  keep dialog active
      return 1;
   }
   
   zdialog_fetch(zd,"repgallery",Frepgallery);                                   //  gallery report 
   zdialog_fetch(zd,"repmeta",Frepmeta);                                         //  metadata report
   zdialog_fetch(zd,"lastver",Flastver);                                         //  get last versions only
   zdialog_fetch(zd,"allvers",Fallvers);                                         //  get all vers. of matching image    18.07

   zdialog_fetch(zd,"datefrom",searchDateFrom,20);                               //  get search date range
   zdialog_fetch(zd,"dateto",searchDateTo,20);
   zdialog_fetch(zd,"photodate",Fphotodate);                                     //  photo or file date                 18.01
   zdialog_fetch(zd,"filedate",Ffiledate);
   zdialog_fetch(zd,"starsfrom",searchStarsFrom,2);                              //  get search stars range
   zdialog_fetch(zd,"starsto",searchStarsTo,2);
   zdialog_fetch(zd,"searchtags",searchtags,tagScc);                             //  get search tags
   zdialog_fetch(zd,"searchtext",searchtext,tagScc);                             //  get search text*
   zdialog_fetch(zd,"searchfiles",searchfiles,tagScc);                           //  get search /path*/file*
   zdialog_fetch(zd,"searchlocs",searchLocations,200);                           //  get search locations

   zdialog_fetch(zd,"alltags",Falltags);                                         //  get match all/any options
   zdialog_fetch(zd,"alltext",Falltext);
   zdialog_fetch(zd,"allfiles",Fallfiles);
   zdialog_fetch(zd,"alllocs",Falllocs);                                         //  17.08
   
   Fdates = 0;
   if (*searchDateFrom) Fdates++;                                                //  search date from was given
   else strcpy(searchDateFrom,dateLoDefault);                                    //  else search from start of time

   if (*searchDateTo) Fdates++;                                                  //  search date to was given
   else strcpy(searchDateTo,dateHiDefault);                                      //  else search to end of time

   Fnulldate = 0;
   if (strmatchcase(searchDateFrom,"null")) {                                    //  search for missing photo date      18.07
      Fnulldate = 1;
      Fdates = Ffiledate = Fphotodate = 0;
      zdialog_stuff(zd,"photodate",1);
      zdialog_stuff(zd,"filedate",0);
   }
   
   if (Fdates)                                                                   //  complete partial date/time data
   {
      cc = strlen(searchDateFrom);
      for (ii = cc; ii < 20; ii++)                                               //  default date from:
         searchDateFrom[ii] = dateLoDefault[ii];                                 //    0000-01-01 00:00:00

      cc = strlen(searchDateTo);
      for (ii = cc; ii < 20; ii++)                                               //  default date to:
         searchDateTo[ii] = dateHiDefault[ii];                                   //    2099-12-31 23:59:59

      if (cc == 7) {                                                             //  input was yyyy-mm                  18.07
         strncpy(mm,searchDateTo+5,2);                                           //  get mm = "01" .. "12"
         if (strstr("04 06 09 11",mm)) strncpy(searchDateTo+8,"30",2);           //  set dd = 30 for these months
         if (strmatch(mm,"02")) {
            strncpy(searchDateTo+8,"28",2);                                      //  set dd = 28 for month 02
            ii = atoi(searchDateTo);
            if (ii == (ii/4)*4) strncpy(searchDateTo+8,"29",2);                  //  set dd = 29 if leap year
         }
      }

      ff = 0;                                                                    //  check search dates reasonable 
      if (! datetimeOK(searchDateFrom)) ff = 1;                                  //  invalid year/mon/day (e.g. mon 13)
      if (! datetimeOK(searchDateTo)) ff = 1;                                    //    or hour/min/sec (e.g. hour 33)
      if (strcmp(searchDateFrom,searchDateTo) > 0) ff = 1;                       //  search-from date > search-to date  18.07
      if (ff) {
         zmessageACK(Mwin,E2X("search dates not reasonable \n %s  %s"),
                                    searchDateFrom,searchDateTo);
         zd->zstat = 0;
         return 1;
      }

      pp = pdatetime_metadatetime(searchDateFrom);                               //  convert to yyyymmddhhmmss          18.01
      if (! pp) return 1;                                                        //    for metadata comparisons
      strncpy0(searchdatelo,pp,16);
      pp = pdatetime_metadatetime(searchDateTo);
      if (! pp) return 1;
      strncpy0(searchdatehi,pp,16);
   }

   Fstars = 0;
   if (*searchStarsFrom || *searchStarsTo) {
      Fstars = 1;                                                                //  stars was given
      ii = *searchStarsFrom;
      if (! ii) ii = '0';
      if (ii < '0' || ii > '5') Fstars = 0;                                      //  validate inputs
      jj = *searchStarsTo;
      if (! jj) jj = '5';
      if (jj < '0' || jj > '5') Fstars = 0;
      if (jj < ii) Fstars = 0;
      if (! Fstars) {
         zmessageACK(Mwin,E2X("stars range not reasonable"));
         zd->zstat = 0;
         return 1;
      }
   }

   Ffiles = 0;
   if (! blank_null(searchfiles)) Ffiles = 1;                                    //  search path / file (fragment) was given

   Ftext = 0;
   if (! blank_null(searchtext)) Ftext = 1;                                      //  search text was given

   Ftags = 0;
   if (! blank_null(searchtags)) Ftags = 1;                                      //  search tags was given

   Flocs = 0;
   if (*searchLocations) Flocs = 1;                                              //  search locations was given

   Fmeta = 0;
   if (Nsearchkeys) Fmeta = 1;                                                   //  search other metadata was given

   //  Begin search. ------------------------------------------------------------

   if (checkpend("all")) return 1;                                               //  check nothing pending
   Ffuncbusy = 1;
   Fblock = 1;
   m_viewmode(0,"F");

   Nadded = Nremoved = Npver = Nleft = 0;                                        //  image counts
   
   //  Search all images, make NEW image set from matching images.

   if (Fscanall && Fnewset)
   {
      fid = fopen(searchresults_file,"w");                                       //  open output file
      if (! fid) goto filerror;

      for (ii = 0; ii < Nxxrec; ii++)                                            //  loop all index recs
      {
         zmainloop(10);                                                          //  keep GTK alive

         xxrec = xxrec_tab[ii];

         match = searchimages_select(xxrec);                                     //  test against select criteria
         if (match) {                                                            //  all criteria passed
            Nadded++;                                                            //  count matches
            fprintf(fid,"%s\n",xxrec->file);                                     //  save matching filename
            snprintf(paneltext,200,"images found: %d",Nadded);                   //  update progress                    18.07
         }
      }

      fclose(fid);
      Nleft = Nadded;
   }

   //  Search all images, ADD matching images to current image set.

   if (Fscanall && Faddset)
   {
      fid = fopen(searchresults_file,"w");                                       //  open output file
      if (! fid) goto filerror;

      for (ii = 0; ii < navi::Nfiles; ii++)                                      //  scan current gallery
      {
         file = gallery(0,"get",ii);
         if (! file) break;
         if (*file != '!') {                                                     //  skip directories
            fprintf(fid,"%s\n",file);                                            //  add image files to output
            Nleft++;
         }
         zfree(file);                                                            //  free memory
      }

      for (ii = 0; ii < Nxxrec; ii++)                                            //  loop all index recs
      {
         zmainloop(10);                                                          //  keep GTK alive
         
         xxrec = xxrec_tab[ii];

         match = searchimages_select(xxrec);                                     //  test against select criteria
         if (match) {                                                            //  all criteria passed
            Nadded++;                                                            //  count matches
            fprintf(fid,"%s\n",xxrec->file);                                     //  save matching filename
            snprintf(paneltext,200,"images found: %d",Nadded);                   //  update progress                    18.07
         }
      }

      fclose(fid);
      Nleft += Nadded;
   }

   //  Search current image set, KEEP only those meeting search criteria.

   if (Fscancurr && Fnewset)
   {
      fid = fopen(searchresults_file,"w");                                       //  open output file
      if (! fid) goto filerror;

      for (ii = 0; ii < navi::Nfiles; ii++)                                      //  scan current gallery
      {
         zmainloop(10);                                                          //  keep GTK alive

         file = gallery(0,"get",ii);
         if (! file) break;
         if (*file == '!') {                                                     //  skip directories
            zfree(file);
            continue;
         }

         xxrec = get_xxrec(file);
         if (! xxrec) {                                                          //  no image index rec?
            zfree(file);
            continue;
         }

         match = searchimages_select(xxrec);                                     //  test against select criteria
         if (match) {                                                            //  passed
            Nleft++;                                                             //  count retained images
            fprintf(fid,"%s\n",file);                                            //  save retained filename
         }
         else Nremoved++;

         snprintf(paneltext,200,"images removed: %d",Nremoved);                  //  update progress                    18.07
         zfree(file);                                                            //  free memory
      }

      fclose(fid);
   }

   //  Search current image set, REMOVE those meeting search criteria.

   if (Fscancurr && Fremset)
   {
      fid = fopen(searchresults_file,"w");                                       //  open output file
      if (! fid) goto filerror;

      for (ii = 0; ii < navi::Nfiles; ii++)                                      //  scan current gallery
      {
         zmainloop(10);                                                          //  keep GTK alive

         file = gallery(0,"get",ii);
         if (! file) break;
         if (*file == '!') {                                                     //  skip directories
            zfree(file);
            continue;
         }

         xxrec = get_xxrec(file);
         if (! xxrec) {                                                          //  no image index rec?
            zfree(file);
            continue;
         }

         match = searchimages_select(xxrec);                                     //  test against select criteria
         if (! match) {                                                          //  failed
            Nleft++;
            fprintf(fid,"%s\n",file);                                            //  save retained filename
         }
         else Nremoved++;

         snprintf(paneltext,200,"images removed: %d",Nremoved);                  //  update progress                    18.07

         zfree(file);                                                            //  free memory
      }

      fclose(fid);
   }

   //  Remove all but the last version of matching images.

   if (Flastver && Nleft)
   {
      cc = Nleft * sizeof(char *);
      flist = (char **) zmalloc(cc);

      fid = fopen(searchresults_file,"r");                                       //  read file of selected image files
      if (! fid) goto filerror;

      for (ii = 0; ii < Nleft; ii++)                                             //  build file list in memory
      {
         file = fgets_trim(buffer,XFCC,fid);
         if (! file) break;
         flist[ii] = zstrdup(file);
      }

      fclose(fid);

      for (ii = 1; ii < Nleft; ii++)                                             //  scan file list in memory
      {
         pp = strrchr(flist[ii],'/');                                            //  /directory.../filename.v...
         if (! pp) continue;                                                     //  |                     |
         pp = strstr(pp,".v");                                                   //  flist[ii]             pp
         if (! pp) continue;
         cc = pp - flist[ii] + 1;
         if (strmatchN(flist[ii],flist[ii-1],cc)) {                              //  compare each filespec with prior
            zfree(flist[ii-1]);                                                  //  match: remove prior from list
            flist[ii-1] = 0;
         }
      }

      fid = fopen(searchresults_file,"w");                                       //  write remaining file list
      if (! fid) goto filerror;                                                  //    to results file

      Npver = 0;
      for (ii = 0; ii < Nleft; ii++)
      {
         file = flist[ii];
         if (file) {
            fprintf(fid,"%s\n",file);
            zfree(file);
         }
         else Npver++;
      }

      fclose(fid);
      zfree(flist);
      
      if (Fscanall) Nadded -= Npver;                                             //  adjust counts
      if (Fscancurr) Nremoved += Npver;
      Nleft -= Npver;
   }
   
   //  Add all versions of matching images.                                      //  18.07

   if (Fallvers && Nleft)
   {
      cc = Nleft * sizeof(char *);                                               //  first, reduce selected images
      flist = (char **) zmalloc(cc);                                             //    to one version each

      fid = fopen(searchresults_file,"r");                                       //  read file of selected image files
      if (! fid) goto filerror;

      for (ii = 0; ii < Nleft; ii++)                                             //  build file list in memory
      {
         file = fgets_trim(buffer,XFCC,fid);
         if (! file) break;
         flist[ii] = zstrdup(file);
      }

      fclose(fid);

      for (ii = 1; ii < Nleft; ii++)                                             //  scan file list in memory
      {
         pp = strrchr(flist[ii],'/');                                            //  /directory.../filename.v...
         if (! pp) continue;                                                     //  |                     |
         pp = strstr(pp,".v");                                                   //  flist[ii]             pp
         if (! pp) continue;
         cc = pp - flist[ii] + 1;
         if (strmatchN(flist[ii],flist[ii-1],cc)) {                              //  compare each filespec with prior
            zfree(flist[ii-1]);                                                  //  match: remove prior from list
            flist[ii-1] = 0;
         }
      }

      fid = fopen(searchresults_file,"w");                                       //  write remaining file list
      if (! fid) goto filerror;                                                  //    to results file

      Npver = 0;
      for (ii = 0; ii < Nleft; ii++)
      {
         if (flist[ii]) {
            fprintf(fid,"%s\n",flist[ii]);
            zfree(flist[ii]);
         }
         else Npver++;
      }

      fclose(fid);
      zfree(flist);
      
      if (Fscanall) Nadded -= Npver;                                             //  adjust counts
      if (Fscancurr) Nremoved += Npver;
      Nleft -= Npver;

      flist = (char **) zmalloc(maxgallery);                                     //  new list for all versions

      fid = fopen(searchresults_file,"r");                                       //  read file of selected image files
      if (! fid) goto filerror;

      for (ii = jj = 0; ii < Nleft && jj < maxgallery; ii++)                     //  get all versions for selected files
      {
         file = fgets_trim(buffer,XFCC,fid);
         ftf = 1;
         while ((filever = file_all_versions(file,ftf))) {
            flist[jj++] = filever;
            if (jj == maxgallery) break;
         }
      }

      Nleft = jj;
      fclose(fid);
      
      if (jj == maxgallery)
         zmessageACK(Mwin,Bgallerytruncated,maxgallery);
      
      fid = fopen(searchresults_file,"w");                                       //  start new search results file
      if (! fid) goto filerror;

      for (ii = 0; ii < Nleft; ii++)                                             //  write all versions to file
      {
         fprintf(fid,"%s\n",flist[ii]);
         zfree(flist[ii]);
      }

      fclose(fid);
      zfree(flist);
   }
   
   //  Search complete. ---------------------------------------------------------

   zmessageACK(Mwin,E2X("images added: %d  removed: %d  new count: %d"),
                           Nadded, Nremoved, Nleft);
   *paneltext = 0;                                                               //  remove progress counter            18.07

   if (Nleft == 0) {
      zmessageACK(Mwin,E2X("no changes made"));
      zd->zstat = 0;                                                             //  stay in search dialog
      Ffuncbusy = 0;
      Fblock = 0;
      return 1;
   }
   
   snprintf(albumfile,200,"%s/Search Results",albums_dirk);                      //  save search results in the
   err = copyFile(searchresults_file,albumfile);                                 //    album "Search Results"           17.08
   if (err) zmessageACK(Mwin,strerror(err));

   free_resources();

   navi::gallerytype = SEARCH;                                                   //  normal search results
   if (Frepmeta) navi::gallerytype = META;                                       //  search results in metadata format  17.04

   gallery(searchresults_file,"initF",0);                                        //  generate gallery of matching files

   if (Frepmeta)                                                                 //  metadata report format
      searchimages_metadata_report();

   Ffuncbusy = 0;
   Fblock = 0;

/***  leave default sort by file name                                            //  18.07

   if (Fphotodate) {                                                             //  select and sort by photo date      18.01
      gallerysort = PDATE;
      galleryseq = ASCEND;
      gallery(0,"sort",-1);
   }

   if (Ffiledate) {                                                              //  select and sort by file mod date   18.01
      gallerysort = FDATE;
      galleryseq = ASCEND;
      gallery(0,"sort",-1);
   }

***/

   gallery(0,"paint",0);                                                         //  position at top
   m_viewmode(0,"G");
   return 1;

filerror:
   zmessageACK(Mwin,"file error: %s",strerror(errno));
   Ffuncbusy = 0;
   Fblock = 0;
   *paneltext = 0;
   return 1;
}


//  Test a given image against selection criteria, return match status.

int searchimages_select(xxrec_t *xxrec)
{
   int  searchimages_metadata_select(xxrec_t *xxrec);

   cchar    *pps, *ppf;
   int      iis, iif;
   int      Nmatch, Nnomatch;

   if (Ffiles)                                                                   //  file name match is wanted
   {
      Nmatch = Nnomatch = 0;

      for (iis = 1; ; iis++)
      {
         pps = strField(searchfiles,' ',iis);                                    //  step thru search file names
         if (! pps) break;
         ppf = strcasestr(xxrec->file,pps);                                      //  compare image file name
         if (ppf) Nmatch++;
         else Nnomatch++;
      }

      if (Nmatch == 0) return 0;                                                 //  no match any file
      if (Fallfiles && Nnomatch) return 0;                                       //  no match all files (dir & file names)
   }

   if (Fnulldate && ! strmatch(xxrec->pdate,"null")) return 0;                   //  null photo date is wanted          18.07

   if (Fdates)                                                                   //  date match is wanted
   {
      if (Fphotodate) {
         if (strcmp(xxrec->pdate,searchdatelo) < 0) return 0;                    //  test photo date                    18.01
         if (strcmp(xxrec->pdate,searchdatehi) > 0) return 0;
      }

      if (Ffiledate) {                                                           //  test file mode date                18.01
         if (strcmp(xxrec->fdate,searchdatelo) < 0) return 0;
         if (strcmp(xxrec->fdate,searchdatehi) > 0) return 0;
      }
   }

   if (Ftags)                                                                    //  tags match is wanted
   {
      Nmatch = Nnomatch = 0;

      for (iis = 1; ; iis++)                                                     //  step thru search tags
      {
         pps = strField(searchtags,",;",iis);                                    //  delimited
         if (! pps) break;
         if (*pps == ' ') continue;

         for (iif = 1; ; iif++)                                                  //  step thru file tags (delimited)
         {
            ppf = strField(xxrec->tags,",;",iif);
            if (! ppf) { Nnomatch++; break; }                                    //  count matches and fails
            if (*ppf == ' ') continue;
            if (strmatch(pps,ppf)) { Nmatch++; break; }                          //  match
         }
      }

      if (Nmatch == 0) return 0;                                                 //  no match to any tag
      if (Falltags && Nnomatch) return 0;                                        //  no match to all tags
   }

   if (Fstars)                                                                   //  rating (stars) match is wanted
   {
      if (*searchStarsFrom && xxrec->rating[0] < *searchStarsFrom) return 0;
      if (*searchStarsTo && xxrec->rating[0] > *searchStarsTo) return 0;
   }

   if (Ftext)                                                                    //  text match is wanted
   {
      Nmatch = Nnomatch = 0;

      for (iis = 1; ; iis++)                                                     //  step through search words
      {
         pps = strField(searchtext,' ',iis);
         if (! pps) break;
         if (*pps == ' ') continue;

         ppf = strcasestr(xxrec->capt,pps);                                      //  match words in captions and comments
         if (! ppf) ppf = strcasestr(xxrec->comms,pps);

         if (ppf) Nmatch++;
         else Nnomatch++;
      }
      
      if (Nmatch == 0) return 0;                                                 //  no match to any word
      if (Falltext && Nnomatch) return 0;                                        //  no match to all words
   }

   if (Flocs )                                                                   //  location match is wanted
   {
      Nmatch = Nnomatch = 0;

      for (iis = 1; ; iis++)                                                     //  step thru search locations
      {
         pps = strField(searchLocations,", ",iis);                               //  comma or blank delimiter 
         if (! pps) break;
         if (*pps == ' ') continue;
         if (strcasestr(xxrec->location,pps)) Nmatch++;                          //  all/any logic                      17.08
         else if (strcasestr(xxrec->country,pps)) Nmatch++;
         else Nnomatch++;
      }

      if (! Nmatch) return 0;                                                    //  no match found
      if (Falllocs && Nnomatch) return 0;
   }

   if (Fmeta)                                                                    //  other metadata match
      if (! searchimages_metadata_select(xxrec)) return 0;

   return 1;
}


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

//  dialog to get metadata search criteria

int searchimages_metadata_dialog(zdialog *zdp)                                   //  overhauled
{
   int searchimages_metadata_dialog_event(zdialog *zd, cchar *event);

   cchar *metamess = E2X("These items are always reported: \n"
                         "date, stars, tags, caption, comment");
   zdialog  *zd;
   int      ii, jj, zstat;
   char     matchx[8] = "matchx";

/***
         Search and Report Metadata

         These items are always reported:
         date, stars, tags, caption, comment

            Additional Items for Report
            Keyword                   Match Criteria
         [__________] [ matches  ] [__________________]
         [__________] [ contains ] [__________________]
         [__________] [  equal   ] [__________________]
         [__________] [  less    ] [__________________]
         [__________] [ greater  ] [__________________]

                   [clear] [apply] [cancel]
***/

   zd = zdialog_new("Search and Report Metadata",Mwin,Bclear,Bapply,Bcancel,null);
   zdialog_add_widget(zd,"label","labmeta","dialog",metamess,"space=5");
   zdialog_add_widget(zd,"label","labopts","dialog",E2X("Additional Items for Report"));

   zdialog_add_widget(zd,"hbox","hb1","dialog");
   zdialog_add_widget(zd,"vbox","vb1","hb1",0,"space=5|homog");
   zdialog_add_widget(zd,"vbox","vb2","hb1",0,"space=5|homog");
   zdialog_add_widget(zd,"vbox","vb3","hb1",0,"space=5|homog|expand");

   zdialog_add_widget(zd,"label","lab1","vb1",E2X("Keyword"));
   zdialog_add_widget(zd,"zentry","key0","vb1");
   zdialog_add_widget(zd,"zentry","key1","vb1");
   zdialog_add_widget(zd,"zentry","key2","vb1");
   zdialog_add_widget(zd,"zentry","key3","vb1");
   zdialog_add_widget(zd,"zentry","key4","vb1");

   zdialog_add_widget(zd,"label","lab2","vb2");
   zdialog_add_widget(zd,"combo","match0","vb2");
   zdialog_add_widget(zd,"combo","match1","vb2");
   zdialog_add_widget(zd,"combo","match2","vb2");
   zdialog_add_widget(zd,"combo","match3","vb2");
   zdialog_add_widget(zd,"combo","match4","vb2");

   zdialog_add_widget(zd,"label","lab3","vb3",E2X("Match Criteria"));
   zdialog_add_widget(zd,"zentry","value0","vb3",0,"expand");
   zdialog_add_widget(zd,"zentry","value1","vb3",0,"expand");
   zdialog_add_widget(zd,"zentry","value2","vb3",0,"expand");
   zdialog_add_widget(zd,"zentry","value3","vb3",0,"expand");
   zdialog_add_widget(zd,"zentry","value4","vb3",0,"expand");

   if (! searchkeys[0])                                                          //  first call initialization
   {
      for (ii = 0; ii < 5; ii++) {
         searchkeys[ii] = (char *) zmalloc(40);
         searchvals[ii] = (char *) zmalloc(100);
         *searchkeys[ii] = *searchvals[ii] = 0;
      }
   }
   
   for (ii = 0; ii < 5; ii++) {
      matchx[5] = '0' + ii;
      zdialog_cb_app(zd,matchx,"matches");
      zdialog_cb_app(zd,matchx,"contains");
      zdialog_cb_app(zd,matchx,"number =");
      zdialog_cb_app(zd,matchx,"number =>");
      zdialog_cb_app(zd,matchx,"number <=");
   }
   
   zdialog_show(zdp,0);                                                          //  hide parent dialog
   zdialog_resize(zd,600,0);
   zdialog_restore_inputs(zd);                                                   //  preload prior user inputs
   zdialog_run(zd,searchimages_metadata_dialog_event,"parent");                  //  run dialog
   zstat = zdialog_wait(zd);                                                     //  wait for completion
   zdialog_free(zd);
   zdialog_show(zdp,1);                                                          //  restore parent dialog
   
   if (zstat != 1) return 0;                                                     //  no search criteria entered
   
   for (ii = 0; ii < Nsearchkeys; ii++) {                                        //  loop search keys
      keyindexed[ii] = 0;
      for (jj = 0; jj < Mxmeta; jj++) {                                          //  compare to xmeta keys
         if (! xmeta_keys[jj]) break;
         if (strmatchcase(searchkeys[ii],xmeta_keys[jj]))
            keyindexed[ii] = 1;                                                  //  found, search key is indexed
      }
   }

   allkeysindexed = 1;                                                           //  all search keys indexed
   for (ii = 0; ii < Nsearchkeys; ii++)
      if (! keyindexed[ii]) allkeysindexed = 0;                                  //  NOT

   return 1;
}


//  dialog event and completion callback function

int searchimages_metadata_dialog_event(zdialog *zd, cchar *event)                //  overhauled
{
   int      ii, jj, err;
   float    fnum;
   char     keyx[8] = "keyx", valuex[8] = "valuex", matchx[8] = "matchx";
   char     temp[100];

   if (! zd->zstat) return 1;                                                    //  wait for completion

   if (zd->zstat == 1) {
      for (ii = 0; ii < 5; ii++) {                                               //  clear
         keyx[3] = '0' + ii;
         valuex[5] = '0' + ii;
         matchx[5] = '0' + ii;
         zdialog_stuff(zd,keyx,"");
         zdialog_stuff(zd,valuex,"");
         zdialog_stuff(zd,matchx,"matches");
         zd->zstat = 0;                                                          //  keep dialog active
      }
      return 1;
   }

   if (zd->zstat != 2) {
      Nsearchkeys = 0;                                                           //  no search keys
      return 1;
   }

   Nsearchkeys = 0;                                                              //  apply

   for (ii = jj = 0; ii < 5; ii++)
   {
      keyx[3] = '0' + ii;                                                        //  get search key
      zdialog_fetch(zd,keyx,searchkeys[ii],40);
      strCompress(searchkeys[ii]);                                               //  remove all blanks from key names
      if (*searchkeys[ii] <= ' ') continue;
      memmove(searchkeys[jj],searchkeys[ii],40);                                 //  repack blank keys

      valuex[5] = '0' + ii;
      zdialog_fetch(zd,valuex,searchvals[ii],100);                               //  get corresp. match value
      strTrim2(searchvals[jj],searchvals[ii]);                                   //  trim leading and trailing blanks

      matchx[5] = '0' + ii;
      zdialog_fetch(zd,matchx,temp,20);                                          //  get corresp. match type
      if (strmatch(temp,"matches")) matchtype[jj] = 'm';
      if (strmatch(temp,"contains")) matchtype[jj] = 'c';
      if (strmatch(temp,"number =")) matchtype[jj] = '=';
      if (strmatch(temp,"number =>")) matchtype[jj] = '>';
      if (strmatch(temp,"number <=")) matchtype[jj] = '<';
      
      if (strstr(temp,"number")) {                                               //  check numeric values
         err = convSF(searchvals[jj],fnum);
         if (err) {
            snprintf(temp,100,E2X("bad number: %s"),searchvals[jj]);
            zmessageACK(Mwin,temp);
            zd->zstat = 0;
            return 1;
         }
      }

      if (ii > jj) *searchkeys[ii] = *searchvals[ii] = 0;
      jj++;
   }
   
   Nsearchkeys = jj;                                                             //  keys found, no blanks
   
   if (Nsearchkeys) zd->zstat = 1;                                               //  keys were entered
   else zd->zstat = 2;                                                           //  no keys were entered

   return 1;
}


//  Test image file metadata against metadata select criteria.
//  indexed metadata = xmeta: keyname1=keyvalue1^ keyname2=keyvalue2^ ...

int searchimages_metadata_select(xxrec_t *xxrec)                                 //  18.01
{
   int searchmeta_test1(cchar *keyval, cchar matchtype, cchar *searchvals);

   char        *keyvals[5];
   int         ii, jj, cc, nx = 0, pass = 1;
   cchar       *pps, *ppf;
   char        *file = xxrec->file;
   char        *xmeta = xxrec->xmeta;                                            //  indexed metadata list
   char        xkey[Mxmeta][60], xval[Mxmeta][100];
   
   pps = xmeta;                                                                  //  unpack indexed metadata 
   for (ii = 0; ii < Mxmeta; ii++) {                                             //    to xkey[], xdata[]
      ppf = strchr(pps,'=');
      if (! ppf) break;
      cc = ppf-pps;
      if (cc > 59) break;
      strncpy0(xkey[ii],pps,cc+1);
      pps = ppf + 1;
      ppf = strchr(pps,'^');
      if (! ppf) break;
      cc = ppf - pps;
      if (cc > 99) break;
      strncpy0(xval[ii],pps,cc+1);
      pps = ppf + 1;
      while (*pps == ' ') pps++;
   }
   
   nx = ii;                                                                      //  xmeta keys found

   for (ii = 0; ii < Nsearchkeys; ii++) {                                        //  loop search keys
      for (jj = 0; jj < nx; jj++) {                                              //  find xmeta key
         if (strmatchcase(searchkeys[ii],xkey[jj])) {                            //  if found, test xmeta data
            pass = searchmeta_test1(xval[jj],matchtype[ii],searchvals[ii]);      //    against search criteria
            if (! pass) return 0;                                                //  fail, no more testing needed
            break;
         }
      }
      if (jj == nx && keyindexed[ii]) {                                          //  search key indexed, not present
         pass = searchmeta_test1(0,matchtype[ii],searchvals[ii]);                //  test for "null" select criteria
         if (! pass) return 0;                                                   //  fail
      }
   }

   if (allkeysindexed) return 1;                                                 //  all search keys indexed, pass
   
   exif_get(file,(cchar **) searchkeys,keyvals,Nsearchkeys);                     //  get metadata from image file

   for (ii = 0; ii < Nsearchkeys; ii++) {                                        //  loop search keys
      pass = searchmeta_test1(keyvals[ii],matchtype[ii],searchvals[ii]);         //  test image data 
      if (! pass) break;                                                         //  fail, no more testing needed
   }
      
   for (ii = 0; ii < Nsearchkeys; ii++)                                          //  bugfix: memory leak                18.01
      if (keyvals[ii]) zfree(keyvals[ii]);

   return pass;                                                                  //  all values pass
}


//  test a single metadata key/value against select criteria

int searchmeta_test1(cchar *keyval, cchar matchtype, cchar *searchvals)
{
   int         nth;
   cchar       *pps;
   float       fkey, fval;

   if (! keyval)                                                                 //  no metadata present
   {
      if (strmatch(searchvals,"null")) return 1;                                 //  search for empty data, pass        18.07
      return 0;                                                                  //  fail
   }   

   if (*searchvals <= ' ') return 1;                                             //  no search values, pass

   for (nth = 1; ; nth++)                                                        //  loop all search values
   {
      pps = strField(searchvals,',',nth);                                        //  comma delimiter
      if (! pps) return 0;                                                       //  no more, no match found

      if (matchtype == 'm') {                                                    //  key matches any [wild] value       18.07
         if (MatchWildIgnoreCase(pps,keyval) == 0) return 1;                     //  match not case sensitive
      }

      else if (matchtype == 'c') {                                               //  key contains any value
         if (strcasestr(keyval,pps)) return 1;                                   //  match not case sensitive
      }

      else if (matchtype == '=') {                                               //  numeric key equals any value
         fkey = atof(keyval);
         fval = atof(pps);
         if (fkey == fval) return 1;                                             //  found match
      }

      else if (matchtype == '>') {                                               //  numeric key >= one value
         fkey = atof(keyval);
         fval = atof(pps);
         if (fkey >= fval) return 1;                                             //  found match
      }

      else if (matchtype == '<') {                                               //  numeric key <= one value
         fkey = atof(keyval);
         fval = atof(pps);
         if (fkey <= fval) return 1;                                             //  found match
      }
      
      else return 0;                                                             //  should not happen
   }
   
   return 0;
}


//  Report selected metadata using a gallery window layout
//  with image thumbnails and selected metadata text.

int searchimages_metadata_report()
{
   using namespace navi;

   cchar    *keys1[7] = { exif_date_key, iptc_rating_key, iptc_keywords_key,
                          exif_city_key, exif_country_key,
                          iptc_caption_key, exif_comment_key };
   cchar       *keys[20];
   char        *file, *kvals[20], blank[4] = " ";
   char        text1[2*indexrecl], text2[200];
   int         Nkeys, ii, jj, cc;
   xxrec_t     *xxrec;
   char        *wwhh, *fsize;
   
   if (Gmdlist) printz("*** memory leak Gmdlist[] \n");                          //  18.01

   if (! Nfiles) {
      printz("metadata report, 0 files \n");
      return 0;
   }
   
   cc = Nfiles * sizeof(char *);                                                 //  allocate metadata list
   Gmdlist = (char **) zmalloc(cc);                                              //  Nfiles = curr. gallery files
   memset(Gmdlist,0,cc);                                                         //  Gmdlist = corresp. metadata list

   for (ii = 0; ii < 7; ii++)                                                    //  set first 6 key names, fixed
      keys[ii] = keys1[ii];

   for (ii = 0; ii < Nsearchkeys; ii++)                                          //  remaining key names from user
      keys[ii+7] = searchkeys[ii];

   Nkeys = 7 + Nsearchkeys;                                                      //  total keys to extract
   Gmdrows = Nkeys - 1;                                                          //  report rows (location/country 1 row)
   
   Fbusy_goal = Nfiles;
   Fbusy_done = 0;

   for (ii = 0; ii < Nfiles; ii++)                                               //  loop image gallery files
   {
      zmainloop();                                                               //  keep GTK alive
   
      file = gallery(0,"get",ii);
      if (! file) continue;
      
      xxrec = get_xxrec(file);                                                   //  get size metadata                  18.07
      if (xxrec) {
         wwhh = xxrec->wwhh;
         fsize = xxrec->fsize;
      }
      else wwhh = fsize = blank;

      exif_get(file,keys,kvals,Nkeys);                                           //  get the metadata

      for (cc = jj = 0; jj < Nkeys; jj++)                                        //  add metadata to report
      {
         if (jj == 0 && kvals[0]) {
            kvals[0][4] = kvals[0][7] = '-';                                     //  conv. yyyy:mm:dd to yyyy-mm-dd
            snprintf(text2,200,"%s:  %s \n",keys[jj], kvals[jj]);
         }
         else if (jj == 1) {
            snprintf(text2,200,"%s: %s   Size: %s  %smb\n",                      //  Rating: N  size: 1234x2345 12.34mb
                        keys[1], kvals[1], wwhh, fsize);
         }
         else if (jj == 3)                                                       //  combine city and country 
            snprintf(text2,200,"Location:  %s  %s\n",kvals[3],kvals[4]);         //  Location:  xxxxxxxx xxxxxxxxx
         else if (jj == 4) continue;                                             //  skip country
         else 
            snprintf(text2,200,"%s:  %s \n",keys[jj], kvals[jj]);                //  all others

         strcpy(text1+cc,text2);
         cc += strlen(text2);
      }

      Gmdlist[ii] = zstrdup(text1);                                              //  GFlist entry --> Gmdlist entry      18.01
      GFlist[ii].mdindex = ii;                                                   //  (GFlist can be later sorted)

      for (jj = 0; jj < Nkeys; jj++)                                             //  free memory
         if (kvals[jj]) zfree(kvals[jj]);

      zfree(file);
      Fbusy_done++;
   }

   Fbusy_goal = Fbusy_done = 0;

   gallerytype = META;                                                           //  gallery type = search results/metadata
   return 0;
}


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

//  Convert pretty date/time format from "yyyy-mm-dd" and "hh:mm:ss" to "yyyymmdd" and "hhmmss".
//  Missing month or day ("yyyy" or "yyyy-mm") is replaced with "-01".
//  Missing seconds ("hh:mm") are replaced with zero ("hh:mm:00").
//  Output user message and return null if not valid.

char * pdate_metadate(cchar *pdate)                                              //  "yyyy-mm-dd" >> "yyyymmdd"
{
   int         monlim[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   int         cc, year, mon, day;
   char        pdate2[12];
   static char mdate[12];

   cc = strlen(pdate);
   if (cc > 10) goto badformat;

   strcpy(pdate2,pdate);

   if (cc == 4)                                                                  //  conv. "yyyy" to "yyyy-01-01"
      strcat(pdate2,"-01-01");
   else if (cc == 7)                                                             //  conv. "yyyy-mm" to "yyyy-mm-01"
      strcat(pdate2,"-01");

   if (strlen(pdate2) != 10) goto badformat;
   if (pdate2[4] != '-' || pdate2[7] != '-') goto badformat;

   year = atoi(pdate2);
   mon = atoi(pdate2+5);
   day = atoi(pdate2+8);

   if (year < 0 || year > 2999) goto baddate;
   if (mon < 1 || mon > 12) goto baddate;
   if (day < 1 || day > monlim[mon-1]) goto baddate;
   if (mon == 2 && day == 29 && (year % 4)) goto baddate;

   memcpy(mdate,pdate2,4);                                                       //  return "yyyymmdd"
   memcpy(mdate+4,pdate2+5,2);
   memcpy(mdate+6,pdate2+8,3);
   return mdate;

badformat:
   zmessageACK(Mwin,E2X("date format is YYYY-MM-DD"));
   return 0;

baddate:
   zmessageACK(Mwin,E2X("date is invalid"));
   return 0;
}


char * ptime_metatime(cchar *ptime)                                              //  "hh:mm[:ss]" >> "hhmmss"
{
   int         cc, hour, min, sec;
   char        ptime2[12];
   static char mtime[8];

   cc = strlen(ptime);
   if (cc > 8) goto badformat;

   strcpy(ptime2,ptime);

   if (cc == 5) strcat(ptime2,":00");                                            //  conv. "hh:mm" to "hh:mm:00"

   if (strlen(ptime2) != 8) goto badformat;
   if (ptime2[2] != ':' || ptime2[5] != ':') goto badformat;

   hour = atoi(ptime2);
   min = atoi(ptime2+3);
   sec = atoi(ptime2+6);
   if (hour < 0 || hour > 23) goto badtime;
   if (min < 0 || min > 59) goto badtime;
   if (sec < 0 || sec > 59) goto badtime;

   memcpy(mtime,ptime2,2);                                                       //  return "hhmmss"
   memcpy(mtime+2,ptime2+3,2);
   memcpy(mtime+4,ptime2+6,2);
   return mtime;

badformat:
   zmessageACK(Mwin,E2X("time format is HH:MM [:SS]"));
   return 0;

badtime:
   zmessageACK(Mwin,E2X("time is invalid"));
   return 0;
}


//  convert yyyy-mm-dd hh:mm[:ss] to yyyymmddhhmmss

char * pdatetime_metadatetime(cchar *pdatetime)
{
   char        pdate[12], ptime[12];
   static char metadatetime[20];
   char        *pp;
   int         cc;
   
   strncpy0(pdate,pdatetime,11);                                                 //  yyyy-mm-dd
   strncpy0(ptime,pdatetime+11,9);                                               //  hh:mm[:ss]

   cc = strlen(ptime);
   if (cc == 5) strcat(ptime,":00");                                             //  hh:mm >> hh:mm:00
   else if (cc != 8) return 0;

   pp = pdate_metadate(pdate);
   if (! pp) return 0;
   strncpy0(metadatetime,pp,9);

   pp = ptime_metatime(ptime);
   if (! pp) return 0;
   strncpy0(metadatetime+8,pp,7);
   
   return metadatetime;
}


//  Convert metadata date/time "yyyymmddhhmmss" to pretty format "yyyy-mm-dd" and "hh:mm:ss"

void metadate_pdate(cchar *metadate, char *pdate, char *ptime)
{
   if (*metadate) {
      memcpy(pdate,metadate,4);                                                  //  yyyymmdd to yyyy-mm-dd
      memcpy(pdate+5,metadate+4,2);
      memcpy(pdate+8,metadate+6,2);
      pdate[4] = pdate[7] = '-';
      pdate[10] = 0;

      memcpy(ptime,metadate+8,2);                                                //  hhmmss to hh:mm:ss
      memcpy(ptime+3,metadate+10,2);
      ptime[2] = ':';
      ptime[5] = 0;
      memcpy(ptime+6,metadate+12,2);
      ptime[5] = ':';
      ptime[8] = 0;
   }
   else *pdate = *ptime = 0;                                                     //  missing
   return;
}


//  validate a date/time string formatted "yyyy-mm-dd hh:mm[:ss]"
//  return 0 if bad, 1 if OK
//  valid year is 0000 to 2099

int datetimeOK(char *datetime)                                                   //  format changed                     18.01
{
   int      monlim[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   int      cc, year, mon, day, hour, min, sec;
   
   cc = strlen(datetime);
   if (cc != 16 && cc != 19) return 0;

   if (datetime[4] != '-') return 0;
   if (datetime[7] != '-') return 0;
   if (datetime[13] != ':') return 0;
   if (cc == 19 && datetime[16] != ':') return 0;
      
   year = atoi(datetime);
   mon = atoi(datetime+5);
   day = atoi(datetime+8);
   hour = atoi(datetime+11);
   min = atoi(datetime+14);
   if (cc == 19) sec = atoi(datetime+17);
   else sec = 0;

   if (year < 0 || year > 2099) return 0;
   if (mon < 1 || mon > 12) return 0;
   if (day < 1 || day > monlim[mon-1]) return 0;
   if (mon == 2 && day == 29 && (year % 4)) return 0;
   if (hour < 0 || hour > 23) return 0;
   if (min < 0 || min > 59) return 0;
   if (sec < 0 || sec > 59) return 0;

   return 1;
}


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

//  add input tag to output tag list if not already there and enough room
//  returns:   0 = added OK     1 = already there (case ignored)
//             2 = overflow     3 = bad tag name     4 = null tag

int add_tag(char *tag, char *taglist, int maxcc)
{
   char     *pp1, *pp2, tag1[tagcc];
   int      cc, cc1, cc2;

   if (! tag) return 4;
   strncpy0(tag1,tag,tagcc);                                                     //  remove leading and trailing blanks
   cc = strTrim2(tag1);
   if (! cc) return 4;
   if (utf8_check(tag1)) return 3;                                               //  look for bad characters
   if (strpbrk(tag1,",;:")) return 3;
   strcpy(tag,tag1);

   pp1 = taglist;
   cc1 = strlen(tag);

   while (true)                                                                  //  check if already in tag list
   {
      while (*pp1 == ' ' || *pp1 == ',') pp1++;
      if (! *pp1) break;
      pp2 = pp1 + 1;
      while (*pp2 && *pp2 != ',') pp2++;
      cc2 = pp2 - pp1;
      if (cc2 == cc1 && strmatchcaseN(tag,pp1,cc1)) return 1;
      pp1 = pp2;
   }

   cc2 = strlen(taglist);                                                        //  append to tag list if space enough
   if (cc1 + cc2 + 3 > maxcc) return 2;
   strcpy(taglist + cc2,tag);
   strcpy(taglist + cc2 + cc1, ", ");                                            //  add delimiter + space

   if (taglist == meta_tags) Fmetamod++;                                         //  image tags were changed

   return 0;
}


//  add tag "fotoxx" when an edited image file is saved
//  used by f_save()

int add_tag_fotoxx(cchar *file)                                                  //  17.04
{
   char  fotoxx[8] = "fotoxx";
   add_tag(fotoxx,meta_tags,tagFcc);
   return 1;
}


//  set image ww/hh metadata for change outside of m_meta_edit_main()
//  used by file_save() in case file size is changed

void set_meta_wwhh(int ww, int hh)
{
   snprintf(meta_wwhh,16,"%dx%d",ww,hh);
   return;
}


//  remove tag from taglist, if present
//  returns: 0 if found and deleted, otherwise 1

int del_tag(char *tag, char *taglist)
{
   int         ii, ftcc, atcc, found;
   char        *temptags;
   cchar       *pp;

   temptags = zstrdup(taglist);

   *taglist = 0;
   ftcc = found = 0;

   for (ii = 1; ; ii++)
   {
      pp = strField(temptags,",;",ii);                                           //  next tag
      if (! pp) {
         zfree(temptags);
         if (found && taglist == meta_tags) Fmetamod++;                          //  image tags were changed
         return 1-found;
      }
      if (*pp == ' ') continue;

      if (strmatchcase(pp,tag)) {                                                //  skip matching tag
         found = 1;
         continue;
      }

      atcc = strlen(pp);                                                         //  copy non-matching tag
      strcpy(taglist + ftcc, pp);
      ftcc += atcc;
      strcpy(taglist + ftcc, ", ");                                              //  + delim + blank
      ftcc += 2;
   }
}


//  add new tag to recent tags, if not already.
//  remove oldest to make space if needed.

int add_recentag(char *tag)
{
   int         err;
   char        *pp, temptags[tagRcc];

   err = add_tag(tag,tags_recentags,tagRcc);                                     //  add tag to recent tags

   while (err == 2)                                                              //  overflow
   {
      strncpy0(temptags,tags_recentags,tagRcc);                                  //  remove oldest to make room
      pp = strpbrk(temptags,",;");
      if (! pp) return 0;
      strcpy(tags_recentags,pp+2);                                               //  delimiter + blank before tag
      err = add_tag(tag,tags_recentags,tagRcc);
   }

   return 0;
}


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

//  Load tags_defined file into tags_deftags[ii] => category: tag1, tag2, ...
//  Read image_index recs. and add unmatched tags: => nocatg: tag1, tag2, ...

void load_deftags()
{
   int tags_Ucomp(cchar *tag1, cchar *tag2);

   static int  Floaded = 0;
   FILE *      fid;
   xxrec_t     *xxrec;
   int         ii, jj, ntags, err, cc, tcc;
   int         ncats, catoverflow;
   int         nocat, nocatcc;
   char        tag[tagcc], catg[tagcc];
   char        tagsbuff[tagGcc];
   char        *pp1, *pp2;
   char        ptags[maxtags][tagcc];                                            //  10000 * 50 = 0.5 MB

   if (Floaded) return;                                                          //  use memory tags if already there
   Floaded++;

   for (ii = 0; ii < maxtagcats; ii++)                                           //  clean memory
      tags_deftags[ii] = 0;

   ncats = catoverflow = 0;

   fid = fopen(tags_defined_file,"r");                                           //  read tags_defined file
   if (fid) {
      while (true) {
         pp1 = fgets_trim(tagsbuff,tagGcc,fid);
         if (! pp1) break;
         pp2 = strchr(pp1,':');                                                  //  isolate "category:"
         if (! pp2) continue;                                                    //  no colon
         cc = pp2 - pp1 + 1;
         if (cc > tagcc-1) continue;                                             //  category name too long
         strncpy0(catg,pp1,cc);                                                  //  (for error message)
         if (strlen(pp1) > tagGcc-2) goto cattoobig;                             //  all category tags too long
         pp2++;
         while (*pp2 == ' ') pp2++;
         if (strlen(pp2) < 3) continue;                                          //  category with no tags
         while (*pp2) { 
            if (*pp2 == ';') *pp2 = ',';                                         //  replace ';' with ',' for Fotoxx
            pp2++; 
         }
         tags_deftags[ncats] = zstrdup(pp1);                                     //  tags_deftags[ii]
         ncats++;                                                                //   = category: tag1, tag2, ... tagN,
         if (ncats == maxtagcats) goto toomanycats;
      }
      err = fclose(fid);
      fid = 0;
      if (err) goto deftagsfilerr;
   }

//  sort the categories in ascending order

   for (ii = 0; ii < ncats; ii++)
   for (jj = ii+1; jj < ncats; jj++)
   {
      pp1 = tags_deftags[ii];
      pp2 = tags_deftags[jj];
      if (strcasecmp(pp1,pp2) > 0) {
         tags_deftags[ii] = pp2;
         tags_deftags[jj] = pp1;
      }
   }

//  move category "nocatg" to the end of the list

   for (ii = 0; ii < ncats; ii++)                                                //  18.01
   {
      pp1 = tags_deftags[ii];
      if (strmatchN(pp1,"nocatg:",7)) {
         for (jj = ii; jj < ncats-1; jj++)
            tags_deftags[jj] = tags_deftags[jj+1];
         tags_deftags[jj] = pp1;
         break;
      }
   }

//  if not already there, add category "nocatg" to the end of the list
   
   pp1 = 0;
   if (ncats > 0) pp1 = tags_deftags[ncats-1];                                   //  last tag category           bugfix 18.01.1
   if (pp1 && strmatchN(pp1,"nocatg:",7)) {                                      //  already 'nocatg'
      nocat = ncats - 1;
      nocatcc = strlen(pp1);
      pp2 = (char *) zmalloc(tagGcc);                                            //  re-allocate max. size
      tags_deftags[nocat] = pp2;                                                 //    for following phase
      strcpy(pp2,pp1);
      zfree(pp1);
   }
   else {
      nocat = ncats;                                                             //  add to end of list                 18.01
      ncats++;
      tags_deftags[nocat] = (char *) zmalloc(tagGcc);                            //  allocate max. size
      strcpy(tags_deftags[nocat],"nocatg: ");
      nocatcc = 8;
   }

//  search image index recs for all tags in all images
//  for tags not found in defined tags list, add to 'nocatg' list

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];

      pp1 = xxrec->tags;                                                         //  may be "null,"

      while (true)
      {
         while (*pp1 && strchr(",; ",*pp1)) pp1++;                               //  next image tag start
         if (! *pp1) break;
         pp2 = strpbrk(pp1,",;");                                                //  end
         if (! pp2) pp2 = pp1 + strlen(pp1);
         cc = pp2 - pp1;
         if (cc > tagcc-1) {
            pp1 = pp2;
            continue;                                                            //  ignore huge tag
         }

         strncpy0(tag,pp1,cc+1);                                                 //  look for tag in defined tags
         if (find_deftag(tag)) {
            pp1 = pp2;                                                           //  found
            continue;
         }

         if (nocatcc + cc + 2 > tagGcc-2) {
            catoverflow = 1;                                                     //  nocatg: length limit reached
            break;
         }
         else {
            strcpy(tags_deftags[nocat] + nocatcc, tag);                          //  append tag to list
            nocatcc += cc;
            strcpy(tags_deftags[nocat] + nocatcc, ", ");                         //  + delim + blank
            nocatcc += 2;
         }

         pp1 = pp2;
      }
   }

   if (catoverflow) goto cattoobig;

//  parse all the tags in each category and sort in ascending order

   for (ii = 0; ii < ncats; ii++)
   {
      pp1 = tags_deftags[ii];
      pp2 = strchr(pp1,':');
      if (! pp2) {
         printz("defined tags file format error: %s \n",pp1);                    //  18.01
         continue;
      }
      cc = pp2 - pp1 + 1;
      strncpy0(catg,pp1,cc);
      pp1 = pp2 + 1;
      while (*pp1 == ' ') pp1++;
      tcc = 0;

      for (jj = 0; jj < maxtags; jj++)
      {
         if (! *pp1) break;
         pp2 = strchr(pp1,',');
         if (pp2) cc = pp2 - pp1;
         else cc = strlen(pp1);
         if (cc > tagcc-1) cc = tagcc-1;
         strncpy0(ptags[jj],pp1,cc+1);
         pp1 += cc + 1;
         tcc += cc;
         while (*pp1 == ' ') pp1++;
      }

      ntags = jj;
      if (ntags == maxtags) goto toomanytags;
      HeapSort((char *) ptags,tagcc,ntags,tags_Ucomp);

      pp1 = tags_deftags[ii];
      tcc += strlen(catg) + 2 + 2 * ntags + 2;                                   //  category, all tags, delimiters
      pp2 = (char *) zmalloc(tcc);

      tags_deftags[ii] = pp2;                                                    //  swap memory
      zfree(pp1);

      strcpy(pp2,catg);
      pp2 += strlen(catg);
      strcpy(pp2,": ");                                                          //  pp2 = "category: "
      pp2 += 2;

      for (jj = 0; jj < ntags; jj++)                                             //  add the sorted tags
      {
         strcpy(pp2,ptags[jj]);                                                  //  append tag + delim + blank
         pp2 += strlen(pp2);
         strcpy(pp2,", ");
         pp2 += 2;
      }

      *pp2 = 0;
   }

   return;

toomanycats:
   zmessageACK(Mwin,"more than %d categories",maxtagcats);
   if (fid) fclose(fid);
   return;

cattoobig:
   zmessageACK(Mwin,"category %s is too big",catg);
   if (fid) fclose(fid);
   return;

toomanytags:
   zmessageACK(Mwin,"category %s has too many tags",catg);
   if (fid) fclose(fid);
   return;

deftagsfilerr:
   zmessageACK(Mwin,"tags_defined file error: %s",strerror(errno));
   return;
}


//  compare function for tag sorting

int tags_Ucomp(cchar *tag1, cchar *tag2)
{
   return strcasecmp(tag1,tag2);
}


//  write tags_deftags[] memory data to the defined tags file if any changes were made

void save_deftags()
{
   int         ii, err;
   FILE        *fid;
   
   fid = fopen(tags_defined_file,"w");                                           //  write tags_defined file
   if (! fid) goto deftagserr;

   for (ii = 0; ii < maxtagcats; ii++)
   {
      if (! tags_deftags[ii]) break;
      err = fprintf(fid,"%s\n",tags_deftags[ii]);                                //  each record:
      if (err < 0) goto deftagserr;                                              //    category: tag1, tag2, ... tagN,
   }

   err = fclose(fid);
   if (err) goto deftagserr;
   return;

deftagserr:
   zmessageACK(Mwin,"tags_defined file error: %s",strerror(errno));
   return;
}


//  find a given tag in tags_deftags[]
//  return: 1 = found, 0 = not found

int find_deftag(char *tag)
{
   int      ii, cc;
   char     tag2[tagcc+4];
   char     *pp;

   strncpy0(tag2,tag,tagcc);                                                     //  construct tag + delim + blank
   cc = strlen(tag2);
   strcpy(tag2+cc,", ");
   cc += 2;

   for (ii = 0; ii < maxtagcats; ii++)
   {
      pp = tags_deftags[ii];                                                     //  category: tag1, tag2, ... tagN,
      if (! pp) return 0;                                                        //  not found

      while (pp)
      {
         pp = strcasestr(pp,tag2);                                               //  look for delim + blank + tag + delim
         if (! pp) break;
         if (strchr(",;:", pp[-2])) return 1;                                    //  cat: tag,  or  priortag, tag,
         pp += cc;                                                               //       |                   |
      }                                                                          //       pp                  pp
   }

   return 1;
}


//  add new tag to tags_deftags[] >> category: tag1, tag2, ... newtag,
//  returns:   0 = added OK     1 = not unique (case ignored)
//             2 = overflow     3 = bad name     4 = null/blank tag
//  if tag present under another category, it is moved to new category

int add_deftag(char *catg, char *tag)
{
   int         ii, cc, cc1, cc2;
   char        catg1[tagcc], tag1[tagcc];
   char        *pp1, *pp2;

   if (! catg) strcpy(catg1,"nocatg");
   else strncpy0(catg1,catg,tagcc);
   cc = strTrim2(catg1);                                                         //  remove leading and trailing blanks
   if (! cc) strcpy(catg1,"nocatg");
   if (utf8_check(catg1)) goto badcatname;                                       //  look for bad characters
   if (strpbrk(catg1,",;:\"")) goto badcatname;

   if (! tag) return 4;
   strncpy0(tag1,tag,tagcc);                                                     //  remove leading and trailing blanks
   cc = strTrim2(tag1);
   if (! cc) return 4;
   if (utf8_check(tag1)) goto badtagname;                                        //  look for bad characters
   if (strpbrk(tag1,",;:\"")) goto badtagname;

   del_deftag(tag1);                                                             //  delete tag if already there

   cc1 = strlen(catg1);

   for (ii = 0; ii < maxtagcats; ii++)                                           //  look for given category
   {
      pp1 = tags_deftags[ii];
      if (! pp1) goto newcatg;
      if (! strmatchN(catg1,pp1,cc1)) continue;                                  //  match on "catname:"
      if (pp1[cc1] == ':') goto oldcatg;
   }

newcatg:
   if (ii == maxtagcats) goto toomanycats;
   cc1 = strlen(catg1) + strlen(tag1) + 6;
   pp1 = (char *) zmalloc(cc1);
   *pp1 = 0;
   strncatv(pp1,cc1,catg1,": ",tag1,", ",null);                                  //  category: + tag + delim + blank
   tags_deftags[ii] = tags_deftags[ii-1];                                        //  move "nocatg" record to next slot
   tags_deftags[ii-1] = pp1;                                                     //  insert new record before
   save_deftags();
   return 0;

oldcatg:                                                                         //  logic simplified
   pp2 = pp1 + cc1 + 2;                                                          //  char following "catname: "
   cc1 = strlen(tag1);
   while (true) {
      pp2 = strcasestr(pp2,tag1);                                                //  look for "tagname, "
      if (! pp2) break;                                                          //  not found
      if (strchr(",;",pp2[cc1])) return 1;                                       //  found, tag not unique
      pp2 += cc1;                                                                //  keep searching
   }
   cc2 = strlen(pp1);                                                            //  add new tag to old record
   if (cc1 + cc2 + 4 > tagGcc) goto cattoobig;
   pp2 = zstrdup(pp1,cc1+cc2+4);                                                 //  expand string
   zfree(pp1);
   tags_deftags[ii] = pp2;
   strcpy(pp2+cc2,tag1);                                                         //  old record + tag + delim + blank
   strcpy(pp2+cc2+cc1,", ");
   save_deftags();
   return 0;

badcatname:
   zmessageACK(Mwin,"bad category name");
   return 3;

badtagname:
   zmessageACK(Mwin,"bad tag name");
   return 3;

toomanycats:
   zmessageACK(Mwin,"too many categories");
   return 2;

cattoobig:
   zmessageACK(Mwin,"too many tags");
   return 2;
}


//  delete tag from defined tags list, tags_deftags[]
//  return: 0 = found and deleted, 1 = not found

int del_deftag(char *tag)
{
   int      ii, cc;
   char     tag2[tagcc+4];
   char     *pp, *pp1, *pp2;

   if (! tag || *tag <= ' ') return 1;                                           //  bad tag

   strncpy0(tag2,tag,tagcc);                                                     //  construct tag + delim + blank
   cc = strlen(tag2);
   strcpy(tag2+cc,", ");
   cc += 2;

   for (ii = 0; ii < maxtagcats; ii++)
   {
      pp = tags_deftags[ii];
      if (! pp) return 1;                                                        //  not found

      while (pp)
      {
         pp = strcasestr(pp,tag2);                                               //  look for prior delim or colon
         if (! pp) break;
         if (strchr(",;:", pp[-2])) goto found;                                  //  cat: tag,  or  priortag, tag,
         pp += cc;                                                               //       |                   |
      }                                                                          //       pp                  pp
   }

found:
   for (pp1 = pp, pp2 = pp+cc; *pp2; pp1++, pp2++)                               //  eliminate tag, delim, blank
      *pp1 = *pp2;
   *pp1 = 0;

   return 0;
}


//  Stuff text widget "deftags" with all tags in the given category.
//  If category "ALL", stuff all tags and format by category.

void deftags_stuff(zdialog *zd, cchar *acatg)
{
   GtkWidget      *widget;
   int            ii, ff, cc;
   char           catgname[tagcc+4];
   char           *pp1, *pp2;
   
   widget = zdialog_widget(zd,"deftags");
   textwidget_clear(widget);

   for (ii = 0; ii < maxtagcats; ii++)
   {
      pp1 = tags_deftags[ii];
      if (! pp1) break;
      pp2 = strchr(pp1,':');
      if (! pp2) continue;
      cc = pp2 - pp1;
      if (cc < 1) continue;
      if (cc > tagcc) continue;
      strncpy0(catgname,pp1,cc+1);

      if (! strmatch(acatg,"ALL")) {
         ff = strmatch(catgname,acatg);
         if (! ff) continue;
      }
      
      strcat(catgname,": ");
      textwidget_append(widget,1,catgname);                                      //  "category: " in bold text
      
      pp2++;
      if (*pp2 == ' ') pp2++;
      if (*pp2) textwidget_append(widget,0,pp2);                                 //  "cat1, cat2, ... catN," 
      textwidget_append(widget,0,"\n");
   }

   return;
}


//  Stuff combo box "defcats" with "ALL" + all defined categories

void defcats_stuff(zdialog *zd)
{
   char     catgname[tagcc+2];
   int      ii, cc;
   char     *pp1, *pp2;

   zdialog_cb_clear(zd,"defcats");
   zdialog_cb_app(zd,"defcats","ALL");
   
   for (ii = 0; ii < maxtagcats; ii++)
   {
      pp1 = tags_deftags[ii];
      if (! pp1) break;
      pp2 = strchr(pp1,':');
      if (! pp2) continue;
      cc = pp2 - pp1;
      if (cc < 1) continue;
      if (cc > tagcc) continue;
      strncpy0(catgname,pp1,cc+1);
      zdialog_cb_app(zd,"defcats",catgname);
   }
   
   return;
}


//  report tags defined and not used in any image file

void tag_orphans(GtkWidget *parent)
{
   FILE        *fid;
   xxrec_t     *xxrec;
   int         ii, jj, cc;
   int         Ndeftags;
   char        **deftags;
   char        usedtag[tagcc], tagsbuff[tagGcc];
   char        *pp1, *pp2;

   deftags = (char **) zmalloc(maxtags * sizeof(char *));                        //  allocate memory
   Ndeftags = 0;

   fid = fopen(tags_defined_file,"r");                                           //  read tags_defined file
   if (fid) {
      while (true) {
         pp1 = fgets_trim(tagsbuff,tagGcc,fid);
         if (! pp1) break;
         pp1 = strchr(pp1,':');                                                  //  skip over "category:"
         if (! pp1) continue;
         cc = pp1 - tagsbuff;
         if (cc > tagcc) continue;                                               //  reject bad data (manual edit?)
         pp1++;
         for (ii = 1; ; ii++) {                                                  //  get tags: tag1, tag2, ...
            pp2 = (char *) strField(pp1,",;",ii);
            if (! pp2) break;
            if (strlen(pp2) < 3) continue;                                       //  reject bad data
            if (strlen(pp2) > tagcc) continue;
            deftags[Ndeftags] = zstrdup(pp2);
            Ndeftags++;
         }
      }
      fclose(fid);
   }

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      zmainloop(100);                                                            //  keep GTK alive

      xxrec = xxrec_tab[ii];

      pp1 = xxrec->tags;                                                         //  image tags
      if (! pp1) continue;
      if (strmatchN(pp1,"null",4)) continue;

      while (true)
      {
         while (*pp1 && strchr(",; ",*pp1)) pp1++;                               //  next image tag start
         if (! *pp1) break;
         pp2 = strpbrk(pp1,",;");                                                //  end
         if (! pp2) pp2 = pp1 + strlen(pp1);
         cc = pp2 - pp1;
         if (cc > tagcc-1) {
            pp1 = pp2;
            continue;                                                            //  ignore huge tag
         }

         strncpy0(usedtag,pp1,cc+1);                                             //  used tag, without delimiter

         for (jj = 0; jj < Ndeftags; jj++)                                       //  find in defined tags
            if (strmatch(usedtag,deftags[jj])) break;

         if (jj < Ndeftags) {                                                    //  found
            zfree(deftags[jj]);
            Ndeftags--;
            while (jj < Ndeftags) {                                              //  defined tag is in use
               deftags[jj] = deftags[jj+1];                                      //  remove from list and pack down
               jj++;
            }
         }

         pp1 = pp2;
      }
   }

   popup_report_open(parent,"unused tags",200,200);
   for (ii = 0; ii < Ndeftags; ii++)
      popup_report_write(0,"%s \n",deftags[ii]);
   popup_report_write(0,"%d unused tags \n",Ndeftags);

   for (ii = 0; ii < Ndeftags; ii++)
      zfree(deftags[ii]);
   zfree(deftags);

   return;
}


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

//  image file EXIF/IPTC data >> memory data:
//    meta_pdate, meta_rating, meta_tags, meta_comments, meta_caption,
//    meta_location, meta_country, meta_lati, meta_longi

void load_filemeta(cchar *file)
{
   int      ii, jj, cc, nkey;
   char     *pp;
   cchar    *exifkeys[100] = { exif_date_key, iptc_keywords_key,
                               iptc_rating_key, exif_wwhh_key,
                               exif_comment_key, iptc_caption_key,
                               exif_city_key, exif_country_key,
                               exif_lati_key, exif_longi_key };

   char     *ppv[100], *imagedate, *imagekeywords, *imagestars, *imagewwhh;
   char     *imagecomms, *imagecapt;
   char     *imageloc, *imagecountry, *imagelati, *imagelongi;
   
   strncpy0(p_meta_pdate,meta_pdate,15);                                         //  save for use by edit_metadata
   strncpy0(p_meta_rating,meta_rating,4);                                        //    [Prev] button
   strncpy0(p_meta_tags,meta_tags,tagFcc);
   strncpy0(p_meta_caption,meta_caption,exif_maxcc);
   strncpy0(p_meta_comments,meta_comments,exif_maxcc);
   strncpy0(p_meta_location,meta_location,100);
   strncpy0(p_meta_country,meta_country,100);
   strncpy0(p_meta_lati,meta_lati,20);
   strncpy0(p_meta_longi,meta_longi,20);

   *meta_tags = *meta_pdate = *meta_comments = *meta_caption = 0;
   strcpy(meta_rating,"0");
   *meta_location = *meta_country = *meta_lati = *meta_longi = 0;
   
   nkey = 10;                                                                    //  add keys for indexed metadata      18.01
   for (ii = 0; ii < Mxmeta; ii++) {                                             //    from exifkeys[10];
      if (! xmeta_keys[ii]) break;
      exifkeys[nkey] = xmeta_keys[ii];
      nkey++;
   }
   
   exif_get(file,exifkeys,ppv,nkey);                                             //  get metadata from image file
   imagedate = ppv[0];
   imagekeywords = ppv[1];
   imagestars = ppv[2];
   imagewwhh = ppv[3];
   imagecomms = ppv[4];
   imagecapt = ppv[5];
   imageloc = ppv[6];
   imagecountry = ppv[7];
   imagelati = ppv[8];
   imagelongi = ppv[9];

   if (imagedate) {
      exif_tagdate(imagedate,meta_pdate);                                        //  EXIF date/time >> yyyymmddhhmmss
      zfree(imagedate);
   }

   if (imagekeywords)
   {
      for (ii = 1; ; ii++)
      {
         pp = (char *) strField(imagekeywords,",;",ii);
         if (! pp) break;
         if (*pp == ' ') continue;
         cc = strlen(pp);
         if (cc >= tagcc) continue;                                              //  reject tags too big
         for (jj = 0; jj < cc; jj++)
            if (pp[jj] > 0 && pp[jj] < ' ') break;                               //  reject tags with control characters
         if (jj < cc) continue;
         add_tag(pp,meta_tags,tagFcc);                                           //  add to file tags if unique
      }

      zfree(imagekeywords);
   }

   if (imagestars) {
      meta_rating[0] = *imagestars;
      if (meta_rating[0] < '0' || meta_rating[0] > '5') meta_rating[0] = '0';
      meta_rating[1] = 0;
      zfree(imagestars);
   }

   if (imagewwhh) {
      strncpy0(meta_wwhh,imagewwhh,15);
      zfree(imagewwhh);
   }

   if (imagecomms) {
      strncpy0(meta_comments,imagecomms,exif_maxcc);
      zfree(imagecomms);
   }

   if (imagecapt) {
      strncpy0(meta_caption,imagecapt,exif_maxcc);
      zfree(imagecapt);
   }

   if (imageloc) {                                                               //  geotags
      strncpy0(meta_location,imageloc,99);
      zfree(imageloc);
   }
   else strcpy(meta_location,"null");                                            //  replace missing data with "null"

   if (imagecountry) {
      strncpy0(meta_country,imagecountry,99);
      zfree(imagecountry);
   }
   else strcpy(meta_country,"null");

   if (imagelati) {
      strncpy0(meta_lati,imagelati,12);
      zfree(imagelati);
   }
   else strcpy(meta_lati,"null");

   if (imagelongi) {
      strncpy0(meta_longi,imagelongi,12);
      zfree(imagelongi);
   }
   else strcpy(meta_longi,"null");

   for (ii = 0; ii < Mxmeta; ii++) {                                             //  get indexed metadata if any        18.01
      if (! xmeta_keys[ii]) break;
      if (xmeta_data[ii]) zfree(xmeta_data[ii]);
      if (ppv[ii+10]) xmeta_data[ii] = ppv[ii+10];
      else xmeta_data[ii] = zstrdup("null");
   }

   Fmetamod = 0;                                                                 //  no pending changes
   return;
}


//  add metadata in memory to image file EXIF/IPTC data and image_index recs.

void save_filemeta(cchar *file)
{
   cchar    *exifkeys[100] = { exif_date_key, iptc_keywords_key, iptc_rating_key, 
                               exif_comment_key, iptc_caption_key,
                               exif_city_key, exif_country_key,
                               exif_lati_key, exif_longi_key };
   int      nkey, ii;
   cchar    *exifdata[100];
   char     imagedate[24];

   *imagedate = 0;
   if (*meta_pdate) tag_exifdate(meta_pdate,imagedate);                          //  yyyymmddhhmmss >> EXIF date/time

   exifdata[0] = imagedate;                                                      //  update file EXIF/IPTC data
   exifdata[1] = meta_tags;
   exifdata[2] = meta_rating;
   exifdata[3] = meta_comments;
   exifdata[4] = meta_caption;

   if (*meta_location < ' ' || strmatch(meta_location,"null"))                   //  geotags
      exifdata[5] = "";
   else exifdata[5] = meta_location;                                             //  if "null" erase EXIF

   if (*meta_country < ' ' || strmatch(meta_country,"null")) 
      exifdata[6] = "";
   else exifdata[6] = meta_country;

   if (*meta_lati < ' ' || strmatch(meta_lati,"null") || 
       *meta_longi < ' ' || strmatch(meta_longi,"null")) 
      exifdata[7] = exifdata[8] = "";
   else {
      exifdata[7] = meta_lati;
      exifdata[8] = meta_longi;
   }
   
   nkey = 9;                                                                     //  add keys for indexed metadata      18.01
   for (ii = 0; ii < Mxmeta; ii++) {                                             //    from exifkeys[9];
      if (! xmeta_keys[ii]) break;
      if (strmatch(xmeta_data[ii],"null")) continue;                             //  18.07
      exifkeys[nkey] = xmeta_keys[ii];
      exifdata[nkey] = xmeta_data[ii];
      nkey++;
   }

   exif_put(file,exifkeys,exifdata,nkey);                                        //  write EXIF

   update_image_index(file);                                                     //  update image index file

   if (zdexifview) meta_view(0);                                                 //  live EXIF/IPTC update

   Fmetamod = 0;                                                                 //  no pending changes 
   return;
}


//  update image index record (replace updated file data)
//  meta_xxxx data in memory >> image index record

void update_image_index(cchar *file)
{
   int      ii, err, xcc;
   char     xmetarec[1000];
   xxrec_t  xxrec;
   STATB    statb;
   
   err = stat(file,&statb);
   if (err) {
      zmessageACK(Mwin,Bfilenotfound);
      return;
   }

   memset(&xxrec,0,sizeof(xxrec_t));                                             //  new metadata record to make

   xxrec.file = (char *) file;                                                   //  image filespec

   compact_time(statb.st_mtime,xxrec.fdate);                                     //  convert file date to "yyyymmddhhmmss"
   strncpy0(xxrec.pdate,meta_pdate,15);                                          //  photo date, "yyyymmddhhmmss"

   xxrec.rating[0] = meta_rating[0];                                             //  rating '0' to '5' stars
   xxrec.rating[1] = 0;

   strncpy0(xxrec.wwhh,meta_wwhh,15);                                            //  2345x1234
   
   snprintf(xxrec.fsize,15,"%.2f",1.0 * statb.st_size / MEGA);                   //  18.07

   if (*meta_tags)                                                               //  tags
      xxrec.tags = meta_tags;

   if (*meta_caption)                                                            //  user caption
      xxrec.capt = meta_caption;

   if (*meta_comments)                                                           //  user comments
      xxrec.comms = meta_comments;

   if (*meta_location <= ' ') strcpy(meta_location,"null");                      //  geotags
   if (*meta_country <= ' ') strcpy(meta_country,"null");
   if (*meta_lati <= ' ') strcpy(meta_lati,"null");                              //  "null" for location/country is searchable
   if (*meta_longi <= ' ') strcpy(meta_longi,"null");
   
   xxrec.location = meta_location;
   xxrec.country = meta_country;
   
   if (strmatch(meta_lati,"null") || strmatch(meta_longi,"null"))
      xxrec.flati = xxrec.flongi = 0;
   else {
      xxrec.flati = atof(meta_lati);
      xxrec.flongi = atof(meta_longi);
      if (xxrec.flati < -90.0 || xxrec.flati > 90.0) 
         xxrec.flati = xxrec.flongi = 0;
      if (xxrec.flongi < -180.0 || xxrec.flongi > 180.0) 
         xxrec.flati = xxrec.flongi = 0;
   }

   xcc = 0;

   for (ii = 0; ii < Mxmeta; ii++) {                                             //  add indexed metadata if any        18.01
      if (! xmeta_keys[ii]) break;
      if (strlen(xmeta_keys[ii]) + strlen(xmeta_data[ii]) > 100) continue;       //  impractical for image search
      strcpy(xmetarec+xcc,xmeta_keys[ii]);                                       //  construct series
      xcc += strlen(xmeta_keys[ii]);                                             //    "keyname=keydata^ "
      xmetarec[xcc++] = '=';
      strcpy(xmetarec+xcc,xmeta_data[ii]);
      xcc += strlen(xmeta_data[ii]); 
      strcpy(xmetarec+xcc,"^ ");
      xcc += 2;
      if (xcc > 895) {
         printz("file metadata exceeds record size: %s \n",file);
         break;
      }
   }

   if (xcc > 0) xxrec.xmeta = zstrdup(xmetarec);
   else xxrec.xmeta = zstrdup("null");

   put_xxrec(&xxrec,file);                                                       //  update image index
   gallery(file,"update",0);                                                     //  update gallery record

   return;
}


//  delete given image file from image index recs.

void delete_image_index(cchar *file)
{
   put_xxrec(null,file);
   return;
}


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

//  Convert a location [country] to earth coordinates using the
//    MapQuest geocoding service.
//  (incomplete names may be completed with a bad guess)

cchar * web_geocode(zdialog *zd)
{
   int         err;
   static char lati[20], longi[20];
   char        outfile[100], URI[300];
   char        *pp1, *pp2, buffer[200];
   char        location[100], country[100];
   float       flati, flongi;
   FILE        *fid;
   cchar       *notfound = E2X("not found");
   cchar       *badinputs = E2X("location and country required");
   cchar       *query = "http://open.mapquestapi.com/geocoding/v1/address?"
                        "&key=Fmjtd%7Cluub2qa72d%2C20%3Do5-9u700a"
                        "&maxResults=1"
                        "&outFormat=csv";

   zdialog_fetch(zd,"location",location,100);                                    //  get zdialog inputs
   zdialog_fetch(zd,"country",country,100);
   if (*location <= ' ' || *country <= ' ') return badinputs;
   
   *location = toupper(*location);                                               //  capitalize
   *country = toupper(*country);

   snprintf(outfile,100,"%s/web-data",temp_dirk);
   snprintf(URI,299,"\"%s&location=%s,%s\"",query,location,country);

   err = shell_quiet("wget -T 10 -o /dev/null -O %s %s",outfile,URI);
#ifdef ECOMM
   if (err == 4) err = ECOMM;                                                    //  replace "interrupted system call"
#endif
   if (err) return strerror(err);

   fid = fopen(outfile,"r");                                                     //  get response
   if (! fid) return notfound;
   pp1 = fgets(buffer,200,fid);
   pp1 = fgets(buffer,200,fid);
   fclose(fid);
   if (! pp1) return notfound;
   printz("web geocode: %s \n",buffer);
   
   pp2 = (char *) strField(pp1,",",4);                                           //  look for returned location name
   if (! pp2 || ! *pp2) return notfound;

   pp2 = (char *) strField(pp1,",",7);
   if (! pp2) return notfound;
   strncpy0(lati,pp2,20);

   pp2 = (char *) strField(pp1,",",8);
   if (! pp2) return notfound;
   strncpy0(longi,pp2,20);

   err = validate_latlong(lati,longi,flati,flongi);
   if (err) return notfound;

   pp1 = strchr(lati,'.');                                                       //  keep max. 4 decimal digits
   if (pp1) *(pp1+5) = 0;
   pp1 = strchr(longi,'.');
   if (pp1) *(pp1+5) = 0;

   zdialog_stuff(zd,"lati",lati);                                                //  stuff output to zdialog
   zdialog_stuff(zd,"longi",longi);

   return 0;
}


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

//  Initialize for geotag functions.
//  Load geolocations data into memory from image index table.
//  Returns no. geolocations loaded.

int init_geolocs()
{
   char     location[100], country[100];
   float    flati, flongi;
   double   time0, time1;
   int      yn, cc, ii, jj;
   xxrec_t  *xxrec;
   
   if (Ngeolocs) return Ngeolocs;                                                //  already done

   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return 0;
   }

   time0 = get_seconds();
   Ffuncbusy = 1;

   cc = (Nxxrec+1) * sizeof(geolocs_t *);                                        //  get memory for geolocs table
   geolocs = (geolocs_t **) zmalloc(cc);                                         //  room for Nxxrec entries

   geolocs[0] = (geolocs_t *) zmalloc(sizeof(geolocs_t));                        //  insure one entry
   geolocs[0]->location = zstrdup("null");
   geolocs[0]->country = zstrdup("null");
   geolocs[0]->flati = 0;
   geolocs[0]->flongi = 0;
   Ngeolocs = 1;

   //  populate geolocs from image index table

   for (ii = 0; ii < Nxxrec; ii++)                                               //  loop all index recs
   {
      xxrec = xxrec_tab[ii];
      
      strncpy0(location,xxrec->location,100); 
      strncpy0(country,xxrec->country,100);
      flati = xxrec->flati;
      flongi = xxrec->flongi;

      if (strmatch(location,"null") && strmatch(country,"null")) continue;       //  ignore missing location

      if (Ngeolocs) {
         jj = Ngeolocs - 1;                                                      //  eliminate sequential duplicates
         if (strmatch(location,geolocs[jj]->location) &&
             strmatch(country,geolocs[jj]->country) &&
             flati == geolocs[jj]->flati &&
             flongi == geolocs[jj]->flongi) continue;
      }

      jj = Ngeolocs++;                                                           //  fill next entry in table
      geolocs[jj] = (geolocs_t *) zmalloc(sizeof(geolocs_t));
      geolocs[jj]->location = zstrdup(location);
      geolocs[jj]->country = zstrdup(country);
      geolocs[jj]->flati = flati;
      geolocs[jj]->flongi = flongi;
   }

   if (Ngeolocs > 1)
      HeapSort((char **) geolocs, Ngeolocs, geolocs_compare);                    //  sort

   for (ii = 0, jj = 1; jj < Ngeolocs; jj++)                                     //  eliminate duplicates
   {
      if (strmatch(geolocs[jj]->location,geolocs[ii]->location) &&
          strmatch(geolocs[jj]->country,geolocs[ii]->country) &&
          geolocs[jj]->flati == geolocs[ii]->flati &&
          geolocs[jj]->flongi == geolocs[ii]->flongi)
      {
         zfree(geolocs[jj]->country);                                            //  free redundant entries
         zfree(geolocs[jj]->location);
         zfree(geolocs[jj]);
      }
      else {
         ii++;                                                                   //  count unique entries
         if (ii < jj) geolocs[ii] = geolocs[jj];                                 //  pack down the table
      }
   }
   
   Ngeolocs = ii + 1;                                                            //  final geolocs table size

   time1 = get_seconds() - time0;
   Ffuncbusy = 0;

   printz("%d images, %d locations  %.3f secs. \n",Nxxrec,Ngeolocs,time1);
   return Ngeolocs;
}


//  Compare 2 geolocs records by country, location, latitude, longitude
//  return  <0  0  >0   for   rec1  <  ==  >  rec2.

int  geolocs_compare(cchar *rec1, cchar *rec2)
{
   float    diff;
   int      ii;

   geolocs_t *r1 = (geolocs_t *) rec1;
   geolocs_t *r2 = (geolocs_t *) rec2;
   
   ii = strcmp(r1->country,r2->country);
   if (ii) return ii;

   ii = strcmp(r1->location,r2->location);
   if (ii) return ii;

   if (r1->flati == 0 && r1->flongi == 0) {                                      //  sort missing lat/long last 
      if (r2->flati == 0 && r2->flongi == 0) return 0;
      else return +1;
   }
   
   diff = r1->flati - r2->flati;
   if (diff < 0) return -1;
   if (diff > 0) return +1;

   diff = r1->flongi - r2->flongi;
   if (diff < 0) return -1;
   if (diff > 0) return +1;

   return 0;
}


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

//  find a geolocation from partial zdialog inputs and user choice of options
//  zdialog widgets: location, country, lati, longi
//  location and country are inputs (may be partial leading strings)
//  all four widgets are outputs (found location and geocoordinates)

int find_location(zdialog *zd)
{
   int  find_location_dialog_event(zdialog *zd, cchar *event);

   zdialog     *zd2;
   cchar       *pp;
   GtkWidget   *parent;
   int         cc, ii, jj, kk, Nmatch, zstat, zoomlev;
   int         flocation = 0, fcountry = 0;
   char        location[100], country[100], text[200];
   char        lati[20], longi[20], *matches[20][2];
   float       flati1 = 999, flati2 = -999;
   float       flongi1 = 999, flongi2 = -999;
   float       flatic, flongic, kmrange, fmpp;
   
   init_geolocs();                                                               //  if not already

   zdialog_fetch(zd,"location",location,100);                                    //  get dialog inputs
   zdialog_fetch(zd,"country",country,100);

   if (*location > ' ' && ! strmatch(location,"null")) flocation = 1;            //  one of these must be present
   if (*country > ' ' && ! strmatch(country,"null")) fcountry = 1;
   if (! flocation && ! fcountry) return 0;

   *location = toupper(*location);                                               //  capitalize
   *country = toupper(*country);

   for (ii = Nmatch = 0; ii < Ngeolocs; ii++)                                    //  search for exact location match
   {
      if (flocation && ! strmatchcase(location,geolocs[ii]->location)) continue;
      if (fcountry && ! strmatchcase(country,geolocs[ii]->country)) continue;
      strncpy0(location,geolocs[ii]->location,100);                              //  save matching location
      strncpy0(country,geolocs[ii]->country,100);
      goto found_location;
   }

   for (ii = kk = Nmatch = 0; ii < Ngeolocs; ii++)                               //  search for partial location match
   {
      if (flocation) {
         cc = strlen(location);
         if (! strmatchcaseN(location,geolocs[ii]->location,cc)) continue;
      }
      if (fcountry) {
         cc = strlen(country);
         if (! strmatchcaseN(country,geolocs[ii]->country,cc)) continue;
      }

      for (jj = 0; jj < Nmatch; jj++)                                            //  reject duplicate match
      {
         if (strmatch(geolocs[ii]->location,matches[jj][0]) &&
            (strmatch(geolocs[ii]->country,matches[jj][1]))) break;
      }
      if (jj < Nmatch) continue;
      
      matches[Nmatch][0] = geolocs[ii]->location;                                //  save match
      matches[Nmatch][1] = geolocs[ii]->country;
      if (Nmatch == 20) return 0;                                                //  >20 matches >> no match
      Nmatch++;                                                                  //  count matches
      if (Nmatch == 1) kk = ii;                                                  //  note first match
   }
   
   if (Nmatch == 0) return 0;                                                    //  no matches

   if (Nmatch == 1) {                                                            //  one match
      strncpy0(location,geolocs[kk]->location,100);                              //  save matching location
      strncpy0(country,geolocs[kk]->country,100);
      goto found_location;
   }

   parent = zd->widget[0].widget;
   zd2 = zdialog_new(E2X("choose location"),parent,Bdone,Bcancel,null);          //  multiple matches, start dialog
   zdialog_add_widget(zd2,"comboE","locations","dialog",0,"space=5");
   for (ii = 0; ii < Nmatch; ii++) {                                             //  list locations to choose from
      snprintf(text,200,"%s | %s",matches[ii][0],matches[ii][1]);
      zdialog_cb_app(zd2,"locations",text);
   }

   zdialog_resize(zd2,300,100);
   zdialog_set_modal(zd2);                                                       //  17.08
   zdialog_run(zd2,find_location_dialog_event,"mouse");                          //  run dialog, wait for completion
   zdialog_cb_popup(zd2,"locations");                                            //  open combo box list
   zstat = zdialog_wait(zd2);

   if (zstat != 1) {                                                             //  no choice made
      zdialog_free(zd2);
      return 0;
   }

   zdialog_fetch(zd2,"locations",text,200);
   pp = strField(text,'|',1);
   if (pp) strncpy0(location,pp,100);                                            //  user choice, location and country
   pp = strField(text,'|',2);
   if (pp) strncpy0(country,pp,100);
   strTrim2(location);
   strTrim2(country);
   zdialog_free(zd2);

found_location:

   zdialog_stuff(zd,"location",location);                                        //  return location data to zdialog
   zdialog_stuff(zd,"country",country);

   for (ii = 0; ii < Ngeolocs; ii++)                                             //  search for location & country
   {
      if (strmatchcase(location,geolocs[ii]->location) &&
          strmatchcase(country,geolocs[ii]->country)) 
      {
         if (geolocs[ii]->flati == 0 && geolocs[ii]->flongi == 0) continue;      //  ignore missing values
         if (geolocs[ii]->flati < flati1) flati1 = geolocs[ii]->flati;           //  save range of geocoordinates found
         if (geolocs[ii]->flati > flati2) flati2 = geolocs[ii]->flati;
         if (geolocs[ii]->flongi < flongi1) flongi1 = geolocs[ii]->flongi;
         if (geolocs[ii]->flongi > flongi2) flongi2 = geolocs[ii]->flongi;
      }
   }
   
   if (flati1 == 999) {                                                          //  no match, return nulls
      zdialog_stuff(zd,"lati","null");
      zdialog_stuff(zd,"longi","null");
      return 0;
   }
   
   if (flati1 == flati2 && flongi1 == flongi2) {                                 //  one match, return geocoordinates
      snprintf(lati,20,"%.4f",flati1);                                           //  reformat with std. precision
      snprintf(longi,20,"%.4f",flongi1);
      zdialog_stuff(zd,"lati",lati);
      zdialog_stuff(zd,"longi",longi);
      return 1;
   }
   
   flatic = 0.5 * (flati1 + flati2);                                             //  multiple matches
   flongic = 0.5 * (flongi1 + flongi2);                                          //  center of enclosing rectangle
   kmrange = earth_distance(flati1,flongi1,flati2,flongi2);                      //  length of diagonal
   if (kmrange > 100) kmrange = 100;
   
   for (zoomlev = 12; zoomlev < 20; zoomlev++)                                   //  loop small to large scale 
   {
      fmpp = netmapscale(zoomlev,flatic,flongic);                                //  meters per pixel at zoom level
      fmpp = 0.001 * fmpp * 100.0;                                               //  km span of 100 pixels
      if (fmpp < kmrange) break;                                                 //  stop when kmrange > 100 pixels
   }
   
   netmap_zoomto(flatic,flongic,zoomlev);                                        //  map click --> stuff zdialog lat/long

   return 0;
}


//  dialog event function - get chosen location/country from multiple choices

int find_location_dialog_event(zdialog *zd, cchar *event)
{
   if (strmatch(event,"locations")) zd->zstat = 1;
   return 1;
}


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

//  Update geolocations table  geolocs[*]
//
//  inputs:  location, country, latitude, longitude
//  return value:  0    OK, no geotag revision (incomplete data)
//                 1    OK, no geotag revision (matches existing data)
//                 2    OK, geotag new location/lat/long added
//                -1    error, lat/long bad

int put_geolocs(zdialog *zd)
{
   char        location[100], country[100];
   char        lati[20], longi[20];
   float       flati, flongi;
   int         ii, err, cc, nn, found = 0;

   zdialog_fetch(zd,"location",location,100);                                    //  get location and geocoordinates
   zdialog_fetch(zd,"country",country,100);

   if (*location <= ' ' || strmatch(location,"null")) return 0;                  //  quit here if location not complete
   if (*country <= ' ' || strmatch(country,"null")) return 0;

   *location = toupper(*location);                                               //  capitalize
   *country = toupper(*country);
   zdialog_stuff(zd,"location",location);
   zdialog_stuff(zd,"country",country);

   zdialog_fetch(zd,"lati",lati,20);
   zdialog_fetch(zd,"longi",longi,20);

   err = validate_latlong(lati,longi,flati,flongi);
   if (err) {                                                                    //  1 = missing, 2 = bad
      if (err == 2) {
         zmessageACK(Mwin,E2X("bad latitude/longitude: %s %s"),lati,longi);
         return -1;
      }
      strcpy(lati,"null");                                                       //  replace missing data with "null"
      strcpy(longi,"null");
      flati = flongi = 0;                                                        //  earth coordinates missing value
   }
   else {
      snprintf(lati,20,"%.4f",flati);                                            //  reformat with std. precision
      snprintf(longi,20,"%.4f",flongi);
   }

   for (ii = 0; ii < Ngeolocs; ii++)                                             //  search geotags for location
   {
      if (! strmatchcase(location,geolocs[ii]->location)) continue;              //  case-insensitive compare
      if (! strmatchcase(country,geolocs[ii]->country)) continue;
      if (! strmatch(location,geolocs[ii]->location)) {
         zfree(geolocs[ii]->location);                                           //  revise capitalization
         geolocs[ii]->location = zstrdup(location);
      }
      if (! strmatch(country,geolocs[ii]->country)) {
         zfree(geolocs[ii]->country);
         geolocs[ii]->country = zstrdup(country);
      }
      if (flati == geolocs[ii]->flati && flongi == geolocs[ii]->flongi) found++;
   }
   
   if (found) return 1;
   
   geolocs_t  *geolocsA = (geolocs_t *) zmalloc(sizeof(geolocs_t));
   geolocs_t  **geolocsB;
   
   geolocsA->location = zstrdup(location);                                       //  new geolocs record
   geolocsA->country = zstrdup(country);
   geolocsA->flati = flati;
   geolocsA->flongi = flongi;
   
   cc = (Ngeolocs + 1) * sizeof(geolocs_t *);
   geolocsB = (geolocs_t **) zmalloc(cc);
   
   for (ii = 0; ii < Ngeolocs; ii++) {                                           //  copy geolocs before new geoloc
      nn = geolocs_compare((cchar *) geolocs[ii], (cchar *) geolocsA);
      if (nn > 0) break;
      geolocsB[ii] = geolocs[ii];
   }
   
   geolocsB[ii] = geolocsA;                                                      //  insert new geolocs

   for ( ; ii < Ngeolocs; ii++)                                                  //  copy geolocs after new geoloc
      geolocsB[ii+1] = geolocs[ii];

   zfree(geolocs);                                                               //  geolocs --> new table
   geolocs = geolocsB;
   Ngeolocs += 1;
   
   return 2;
}


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

//  validate and convert earth coordinates, latitude and longitude
//  return: 0  OK
//          1  both are missing ("null")
//          2  invalid data
//  if status is > 0, 0.0 is returned for both values

int validate_latlong(char *lati, char *longi, float &flati, float &flongi)
{
   int      err;
   char     *pp;

   if ((! *lati || *lati == ' ' || strmatch(lati,"null")) && 
       (! *longi || *longi == ' ' || strmatch(longi,"null"))) goto status1;      //  both missing

   if ((! *lati || *lati == ' ' || strmatch(lati,"null")) || 
       (! *longi || *longi == ' ' || strmatch(longi,"null"))) goto status2;      //  one missing
   
   pp = strchr(lati,',');                                                        //  replace comma decimal point
   if (pp) *pp = '.';                                                            //    with period
   pp = strchr(longi,',');
   if (pp) *pp = '.';

   err = convSF(lati,flati,-90,+90);                                             //  convert to float and check limits
   if (err) goto status2;
   err = convSF(longi,flongi,-180,+180);
   if (err) goto status2;

   if (flati == 0.0 && flongi == 0.0) goto status2;                              //  reject both = 0.0
   return 0;

status1:
   flati = flongi = 0.0;                                                         //  both missing
   return 1;

status2:                                                                         //  one missing or invalid
   flati = flongi = 0.0;
   return 2;
}


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

//  compute the km distance between two earth coordinates

float earth_distance(float lat1, float long1, float lat2, float long2)
{
   float    dlat, dlong, mlat, dist;
   
   dlat = fabsf(lat2 - lat1);                                                    //  latitude distance
   dlong = fabsf(long2 - long1);                                                 //  longitude distance
   mlat = 0.5 * (lat1 + lat2);                                                   //  mean latitude
   mlat *= 0.01745;                                                              //  radians
   dlong = dlong * cosf(mlat);                                                   //  longitude distance * cos(latitude)
   dist = sqrtf(dlat * dlat + dlong * dlong);                                    //  distance in degrees
   dist *= 111.0;                                                                //  distance in km
   return dist;
}


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

//  generate a list of files and geocoordinates from the current gallery file list

int get_gallerymap()
{
   int         ii, jj, cc;
   xxrec_t     *xxrec;
   
   if (! navi::Nfiles) {                                                         //  bugfix                             18.07
      zmessageACK(Mwin,E2X("gallery is empty"));
      return 0;
   }

   if (gallerymap) {                                                             //  free prior gallerymap
      for (ii = 0; ii < Ngallerymap; ii++) 
         zfree(gallerymap[ii].file);
      zfree(gallerymap);
      gallerymap = 0;
   }

   cc = sizeof(gallerymap_t);
   gallerymap = (gallerymap_t *) zmalloc(navi::Nfiles * cc);   

   for (jj = 0, ii = navi::Nsubdirs; ii < navi::Nfiles; ii++)                    //  loop gallery files
   {
      xxrec = get_xxrec(navi::GFlist[ii].file);                                  //  look up in xxrec_tab
      if (! xxrec) continue;
      gallerymap[jj].flati = xxrec->flati; 
      gallerymap[jj].flongi = xxrec->flongi;
      gallerymap[jj].file = zstrdup(navi::GFlist[ii].file);
      jj++;
   }

   Ngallerymap = jj;
   return Ngallerymap;
}


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

//  choose to mark map locations for all images or current gallery only

void m_set_map_markers(GtkWidget *, cchar *) 
{
   F1_help_topic = "set_map_markers";
   
   zdialog  *zd;
   int      zstat, showall = 0;

/***
          _____________________________
         |      Set Map Markers        |
         |                             |
         | (o) mark all image files    |
         | (o) mark current gallery    |
         |                             |
         |                    [apply]  |
         |_____________________________|

***/

   zd = zdialog_new(E2X("Set Map Markers"),Mwin,Bapply,null);
   zdialog_add_widget(zd,"radio","all","dialog",E2X("mark all image files"));
   zdialog_add_widget(zd,"radio","gallery","dialog",E2X("mark current gallery"));
   zdialog_stuff(zd,"all",1);
   zdialog_stuff(zd,"gallery",0);

   zdialog_restore_inputs(zd);
   zdialog_resize(zd,200,0);
   zdialog_set_modal(zd);                                                        //  17.08
   zdialog_run(zd,null,"mouse");

   zstat = zdialog_wait(zd);
   if (zstat != 1) {
      zdialog_free(zd);
      return;
   }
   
   zdialog_fetch(zd,"all",showall);                                              //  show all images
   zdialog_free(zd);

   if (showall) {
      if (gallerymap) {                                                          //  free gallerymap
         for (int ii = 0; ii < Ngallerymap; ii++) 
            zfree(gallerymap[ii].file);
         zfree(gallerymap);
         gallerymap = 0;
      }
   }

   else get_gallerymap();                                                        //  show gallery images only
   
   if (FGWM == 'W') Fpaint2();
   if (FGWM == 'M') netmap_paint_dots();

   return;
}


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

//  Map Functions for local file maps (W view)
//  Maps of any scale can be user-installed.
//  Mercator projection is assumed (but unimportant for maps < 100 km).

namespace filemap
{
   char     mapname[100];
   int      mapww, maphh;                                                        //  map width, height
   float    mflati[2];                                                           //  latitude range, low - high
   float    mflongi[2];                                                          //  longitude range, low - high
}

int   filemap_position(float flati, float flongi, int &mx, int &my);             //  earth coordinates > map position
int   filemap_coordinates(int mx, int my, float &flati, float &flongi);          //  map position > earth coordinates
void  find_filemap_images(float flati, float flongi);                            //  find images within range of geolocation


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

//  load the default world map or a map chosen by the user

void m_load_filemap(GtkWidget *, cchar *menu)
{
   using namespace filemap;

   int  load_filemap_dialog_event(zdialog *zd, cchar *event);

   char     mapindex[200], mapfile[200];
   char     buff[200];
   cchar    *pp;
   zdialog  *zd;
   int      err, zstat, yn;
   FILE     *fid;
   float    flati1, flati2, flongi1, flongi2;
   STATB    statb;

   F1_help_topic = "worldmap_view";

   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return;
   }
   
   if (Findexvalid == 1) zmessage_post_bold(Mwin,"20/10",2,Boldindex);           //  warn, index missing new files

   if (! init_geolocs()) return;                                                 //  insure geolocations are loaded

   snprintf(mapindex,200,"%s/maps_index",maps_dirk);                             //  check map index file exists
   err = stat(mapindex,&statb);                                                  //  (from fotoxx-maps package)
   if (err) goto nomapsinstalled;

   if (menu && strmatch(menu,"default")) {
      strcpy(mapname,"World.jpg");                                               //  use default world map
      goto load_map;
   }

   fid = fopen(mapindex,"r");                                                    //  open map index file
   if (! fid) goto nomapsinstalled;
   
   F1_help_topic = "choose_worldmap";

   zd = zdialog_new(E2X("choose map file"),Mwin,Bcancel,null);                   //  start map chooser dialog
   zdialog_add_widget(zd,"combo","mapname","dialog",0,"space=5");

   while (true)
   {
      pp = fgets_trim(buff,200,fid,1);                                           //  get map file names
      if (! pp) break;
      pp = strField(pp,",",1);
      if (! pp) continue;
      zdialog_cb_app(zd,"mapname",pp);                                           //  add to dialog popup list
   }

   fclose(fid);
   
   snprintf(mapindex,200,"%s/maps_index",user_maps_dirk);                        //  look for user map index file
   err = stat(mapindex,&statb);
   if (err) goto choose_worldmap;

   fid = fopen(mapindex,"r");                                                    //  open user map index
   if (fid)
   {
      while (true)   
      {
         pp = fgets_trim(buff,200,fid,1);                                        //  get map file names
         if (! pp) break;
         pp = strField(pp,",",1);
         if (! pp) continue;
         zdialog_cb_app(zd,"mapname",pp);                                        //  add to dialog popup list
      }

      fclose(fid);
   }
   
choose_worldmap:

   if (*mapname && Wstate.fpxb)                                                  //  show current map if any
      zdialog_stuff(zd,"mapname",mapname);

   zdialog_resize(zd,300,100);
   zdialog_set_modal(zd);                                                        //  17.08
   zdialog_run(zd,load_filemap_dialog_event,"mouse");                            //  run dialog, get user choice

   zstat = zdialog_wait(zd);
   if (zstat != 1) {
      zdialog_free(zd);                                                          //  cancel
      return;
   }

   zdialog_fetch(zd,"mapname",mapname,100);                                      //  user choice
   zdialog_free(zd);

load_map:

   snprintf(mapfile,200,"%s/%s",maps_dirk,mapname);                              //  check map file exists
   err = stat(mapfile,&statb);
   if (err) {
      snprintf(mapfile,200,"%s/%s",user_maps_dirk,mapname);                      //  check user maps also
      err = stat(mapfile,&statb);
   }
   if (err) goto mapfilemissing;                                                 //  not found

   snprintf(mapindex,200,"%s/maps_index",maps_dirk);                             //  read map index again
   fid = fopen(mapindex,"r");
   if (! fid) goto nomapsinstalled;

   while (true)
   {
      pp = fgets_trim(buff,200,fid,1);                                           //  find chosen map file
      if (! pp) break;
      pp = strField(buff,",",1);
      if (! pp) continue;
      if (strmatch(pp,mapname)) break;
   }

   fclose(fid);
   if (pp) goto get_lat_long;                                                    //  found

   snprintf(mapindex,200,"%s/maps_index",user_maps_dirk);                        //  read user map index again
   fid = fopen(mapindex,"r");
   if (! fid) goto nomapsinstalled;

   while (true)
   {
      pp = fgets_trim(buff,200,fid,1);                                           //  find chosen map file
      if (! pp) break;
      pp = strField(buff,",",1);
      if (! pp) continue;
      if (strmatch(pp,mapname)) break;
   }

   fclose(fid);
   if (! pp) goto mapfilemissing;                                                //  not found in either index

get_lat_long:

   flati1 = flati2 = flongi1 = flongi2 = 0;

   pp = strField(buff,",",2);                                                    //  get map earth coordinates range
   if (! pp) goto latlongerr;                                                    //    and verify data OK
   err = convSF(pp,flati1,-80,+80);
   if (err) goto latlongerr;

   pp = strField(buff,",",3);
   if (! pp) goto latlongerr;
   err = convSF(pp,flati2,-80,+80);
   if (err) goto latlongerr;

   pp = strField(buff,",",4);
   if (! pp) goto latlongerr;
   err = convSF(pp,flongi1,-200,+200);
   if (err) goto latlongerr;

   pp = strField(buff,",",5);
   if (! pp) goto latlongerr;
   err = convSF(pp,flongi2,-200,+200);
   if (err) goto latlongerr;

   if (flati2 < flati1 + 0.001) goto latlongerr;                                 //  require map range > 100m
   if (flongi2 < flongi1 + 0.001) goto latlongerr;

   printz("load filemap: %s \n",mapname);                                        //  no errors, commit to load map

   free_filemap();                                                               //  free prior map

   Ffuncbusy = 1;
   zmainloop();
   Wstate.fpxb = PXB_load(mapfile,1);                                            //  load map file (with diagnostic)
   Ffuncbusy = 0;
   if (! Wstate.fpxb) return;

   mapww = Wstate.fpxb->ww;                                                      //  save map pixel dimensions
   maphh = Wstate.fpxb->hh;

   mflati[0] = flati1;                                                           //  save map earth coordinates range
   mflati[1] = flati2;
   mflongi[0] = flongi1;
   mflongi[1] = flongi2;

   m_zoom(null,"fit");
   return;

nomapsinstalled:
   zmessageACK(Mwin,E2X("fotoxx-maps package not installed \n"
                        "(see https://kornelix.net)"));
   return;

mapfilemissing:
   zmessageACK(Mwin,E2X("map file %s is missing"),mapname);
   return;

latlongerr:
   zmessageACK(Mwin,E2X("map latitude/longitude data unreasonable \n"
                        " %.3f %.3f %.3f %.3f"),flati1,flati2,flongi1,flongi2);
   return;
}


//  dialog event and completion function

int  load_filemap_dialog_event(zdialog *zd, cchar *event)
{
   if (strmatch(event,"mapname")) zd->zstat = 1;
   return 1;
}


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

//  Convert latitude and longitude into map position px/py.
//  Return 0 if OK, +N if error (off the map).

int filemap_position(float flati, float flongi, int &px, int &py)
{
   using namespace filemap;

   float    flati1, flati2, flongi1, flongi2;
   float    zww, qy, qy2;

   flati1 = mflati[0];                                                           //  map latitude low - high range
   flati2 = mflati[1];
   flongi1 = mflongi[0];                                                         //  map longitude low - high range
   flongi2 = mflongi[1];

   px = py = 0;

   if (flati < flati1 || flati >= flati2) return 1;                              //  flati/flongi outside map limits
   if (flongi < flongi1 || flongi >= flongi2) return 1;

   px = (flongi - flongi1) / (flongi2 - flongi1) * mapww;                        //  return px position

   zww = mapww * 360.0 / (flongi2 - flongi1);                                    //  width for -180 to +180 longitude

   flati1 = flati1 / RAD;                                                        //  convert to radians
   flati2 = flati2 / RAD;
   flati = flati / RAD;

   qy2 = (zww/2/PI) * (log(tan(flati2/2 + PI/4)));                               //  flati2 distance from equator
   qy =  (zww/2/PI) * (log(tan(flati/2 + PI/4)));                                //  flati distance from equator
   py = qy2 - qy;                                                                //  return py position

   if (px < 2 || px > mapww-3) return 1;                                         //  out of bounds
   if (py < 2 || py > maphh-3) return 1;                                         //  includes margins for red dot

   return 0;
}


//  Convert map position px/py into latitude and longitude.
//  Return 0 if OK, +N if error (off the map).

int filemap_coordinates(int px, int py, float &flati, float &flongi)
{
   using namespace filemap;

   float    flati1, flati2, flongi1, flongi2;
   float    zww, qy, qy2;

   flati = flongi = 0;
   if (px < 0 || px > mapww) return 1;                                           //  px/py outside map size
   if (py < 0 || py > maphh) return 1;

   flati1 = mflati[0];                                                           //  map latitude low - high range
   flati2 = mflati[1];
   flongi1 = mflongi[0];                                                         //  map longitude low - high range
   flongi2 = mflongi[1];

   flongi = flongi1 + (1.0 * px / mapww) * (flongi2 - flongi1);                  //  return longitude

   zww = mapww * 360.0 / (flongi2 - flongi1);                                    //  width for -180 to +180 longitude

   flati1 = flati1 / RAD;                                                        //  convert to radians
   flati2 = flati2 / RAD;

   qy2 = (zww/2/PI) * (log(tan(flati2/2 + PI/4)));                               //  lat2 distance from equator
   qy2 = qy2 - py;                                                               //  py distance from equator
   qy = fabsf(qy2);

   flati = 2 * atan(exp(2*PI*qy/zww)) - PI/2;
   if (qy2 < 0) flati = -flati;

   flati = flati * RAD;                                                          //  return latitude
   return 0;
}


//  paint red dots corresponding to image locations on map

void filemap_paint_dots()
{
   int      ii, err;
   int      mx, my, dx, dy;
   float    flati, flongi, radius;
   float    plati = 999, plongi = 999;

   if (! Wstate.fpxb) return;                                                    //  no map loaded

   cairo_t *cr = draw_context_create(gdkwin,draw_context);                       //  17.04

   radius = map_dotsize / 2;

   cairo_set_source_rgb(cr,1,0,0);

   if (gallerymap)                                                               //  use gallerymap[] if present
   {                                                                             //  mark gallery images on map
      for (ii = 0; ii < Ngallerymap; ii++)
      {
         flati = gallerymap[ii].flati;
         flongi = gallerymap[ii].flongi;
         if (flati == plati && flongi == plongi) continue;                       //  skip repititions
         plati = flati;
         plongi = flongi;
         err = filemap_position(flati,flongi,mx,my);
         if (err) continue;
         dx = Cstate->mscale * mx - Cstate->morgx + Cstate->dorgx;
         dy = Cstate->mscale * my - Cstate->morgy + Cstate->dorgy;
         if (dx < 0 || dx > Dww-1) continue;
         if (dy < 0 || dy > Dhh-1) continue;
         cairo_arc(cr,dx,dy,radius,0,2*PI);
         cairo_fill(cr);
      }   
   }
   
   else
   {   
      for (ii = 0; ii < Ngeolocs; ii++)                                          //  mark all image locations on map
      {
         flati = geolocs[ii]->flati;
         flongi = geolocs[ii]->flongi;
         err = filemap_position(flati,flongi,mx,my);
         if (err) continue;
         dx = Cstate->mscale * mx - Cstate->morgx + Cstate->dorgx;
         dy = Cstate->mscale * my - Cstate->morgy + Cstate->dorgy;
         if (dx < 0 || dx > Dww-1) continue;
         if (dy < 0 || dy > Dhh-1) continue;
         cairo_arc(cr,dx,dy,radius,0,2*PI);
         cairo_fill(cr);
      }
   }

   draw_context_destroy(draw_context);                                           //  17.04
   return;
}


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

//  Respond to mouse movement and left clicks on filemap image.
//  Set longitude and latitude, and location and country.
//  Show images near clicked location.

void filemap_mousefunc()
{
   int         err, mx, my, px, py, ii, minii;
   char        *location, *country;
   float       flati, flongi, glati, glongi;
   float       dist, mindist;
   float       mscale = Cstate->mscale;
   int         capturedist = (map_dotsize + 2) / 2;                              //  mouse - marker capture distance
   int         Fusedot = 0;
   static      char  *ploc = 0;
   char        text[20];
   zdialog     *zd = zd_mapgeotags;

   if (checkpend("edit busy block")) return;                                     //  check nothing pending
   if (Cstate != &Wstate) return;                                                //  view mode not world maps
   if ((Mxdrag || Mydrag)) return;                                               //  pan/scroll - handle normally
   if (RMclick) return;                                                          //  zoom - fit window, handle normally
   if (LMclick && mscale < 1) return;                                            //  handle normally if not full size
   if (! Wstate.fpxb) return;

   mx = Mxposn;                                                                  //  mouse position, image space
   my = Myposn;

   err = filemap_coordinates(mx,my,flati,flongi);
   if (err) return;                                                              //  off the map

   dist = mindist = 999999;
   minii = 0;

   for (ii = 0; ii < Ngeolocs; ii++)                                             //  find nearest location/country
   {
      glati = geolocs[ii]->flati;
      dist = (flati - glati) * (flati - glati);
      if (dist > mindist) continue;
      glongi = geolocs[ii]->flongi;
      dist += (flongi - glongi) * (flongi - glongi);                             //  degrees**2
      if (dist > mindist) continue;
      mindist = dist;
      minii = ii;
   }

   ii = minii;
   glati = geolocs[ii]->flati;                                                    //  closest known place
   glongi = geolocs[ii]->flongi;
   location = geolocs[ii]->location;
   country = geolocs[ii]->country;

   err = filemap_position(glati,glongi,px,py);                                   //  corresp. map image position
   dist = sqrtf((px-mx) * (px-mx) + (py-my) * (py-my));
   dist = dist * mscale;                                                         //  (mouse - map) in pixels
   if (dist <= capturedist) Fusedot = 1;                                         //  mouse is within marker dot

   if (LMclick)                                                                  //  left mouse click
   {
      LMclick = 0;

      if (zd)                                                                    //  stuff calling dialog
      {
         if (Fusedot) {                                                          //  click within dot
            zdialog_stuff(zd,"location",location);                               //  use dot location data
            zdialog_stuff(zd,"country",country);
            zdialog_stuff(zd,"lati",glati,"%.5f");                               //  5 decimal places                   18.01
            zdialog_stuff(zd,"longi",glongi,"%.5f");
         }
         else {
            zdialog_stuff(zd,"lati",flati,"%.5f");                               //  use clicked geocoordinaes only
            zdialog_stuff(zd,"longi",flongi,"%.5f");
         }
         zdialog_send_event(zd,"geomap");                                        //  activate calling dialog
         m_viewmode(0,&PFGWM);                                                   //  restore prior view mode            7.10
      }

      else if (location)
         find_filemap_images(flati,flongi);                                      //  show images in range of location

      else {
         snprintf(text,20,"%.5f %.5f",flati,flongi);                             //  show coordinates
         poptext_mouse(text,20,-20,0.1,3);                                       //  18.07
      }
   }

   else if (location && Fusedot) {                                               //  mouse movement, no click
      if (! ploc || ! strmatch(location,ploc)) {                                 //  popup the city/location name at mouse
         poptext_mouse(location,20,-20,0.1,1);                                   //  18.07
         ploc = location;
      }
   }

   else ploc = 0;

   return;
}


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

//  find images within the marker size, show gallery of images.
//  privat function for filemap_mousefunc(), called when a location is clicked

void find_filemap_images(float flati, float flongi)
{
   int         ii, nn = 0;
   int         x1, y1, x2, y2;
   int         capturedist = (map_dotsize + 2) / 2;                              //  mouse - marker capture distance
   float       glati, glongi, grange;
   xxrec_t     *xxrec;
   FILE        *fid;

   filemap_position(flati,flongi,x1,y1);                                         //  target map pixel location

   fid = fopen(searchresults_file,"w");                                          //  open output file
   if (! fid) {
      zmessageACK(Mwin,"output file error: %s",strerror(errno));
      return;
   }
   
   if (gallerymap)                                                               //  show gallery images at location
   {
      for (ii = 0; ii < Ngallerymap; ii++)                                       //  loop all gallery files
      {
         zmainloop(100);                                                         //  keep GTK alive
         
         glati = gallerymap[ii].flati;                                           //  file geocoordinates
         glongi = gallerymap[ii].flongi;
         filemap_position(glati,glongi,x2,y2);                                   //  image map pixel location
         
         grange = sqrtf((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));                      //  target - image pixel distance
         if (grange < 1.5 * capturedist) {                                       //  within distance limit, select
            fprintf(fid,"%s\n",gallerymap[ii].file);                             //  output matching file
            nn++;
         }
      }
   }
   
   else
   {
      for (ii = 0; ii < Nxxrec; ii++)                                            //  show all images at location
      {
         zmainloop(100);                                                         //  keep GTK alive

         xxrec = xxrec_tab[ii];

         glati = xxrec->flati;
         glongi = xxrec->flongi;
         filemap_position(glati,glongi,x2,y2);                                   //  image map pixel location
         
         grange = sqrtf((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));                      //  target - image pixel distance
         if (grange < 1.5 * capturedist) {                                       //  within distance limit, select
            fprintf(fid,"%s\n",xxrec->file);                                     //  output matching file
            nn++;
         }
      }
   }
   
   fclose(fid);

   if (! nn) {
      poptext_mouse(E2X("No matching images found"),10,0,0,3);
      return;
   }

   free_resources();
   navi::gallerytype = SEARCH;                                                   //  search results
   gallery(searchresults_file,"initF",0);                                        //  generate gallery of matching files
   gallery(0,"paint",0);
   m_viewmode(0,"G");

   return;
}


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

//  free memory lorge memory used for filemap image
//  used by edit_setup() to maximize available memory

void free_filemap()
{
   if (Wstate.fpxb) PXB_free(Wstate.fpxb);
   Wstate.fpxb = 0;
   return;
}


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

//  net maps using libchamplain (M view)
//  working map sources: "net-mapnik" "net-transportmap"

namespace netmaps
{
   GtkWidget                   *mapwidget = 0;
   ChamplainView               *mapview = 0;
   ChamplainMapSourceFactory   *map_factory = 0;
   ChamplainMapSource          *map_source = 0;
   ChamplainMarkerLayer        *markerlayer = 0;
   ChamplainMarker             *marker[maximages];
   ClutterColor                *markercolor;
   ChamplainRenderer           *renderer;
   ChamplainMapSource          *error_source;
   ChamplainNetworkTileSource  *tile_source;
   ChamplainFileCache          *file_cache;
   ChamplainMemoryCache        *memory_cache;
   ChamplainMapSourceChain     *source_chain;

// char     *mapbox_access_key;                                                  //  in fotoxx.h 
   cchar    *mapbox_license_text = "";
   cchar    *mapbox_license_uri = "https://www.mapbox.com/tos/";
   cchar    *mapbox_access_uri = "https://api.mapbox.com/v4/mapbox.light/#Z#/#X#/#Y#@2x.jpg70?access_token=";
   int      mapbox_tile_size = 512;
   int      mapbox_min_zoom = 1;                                                 //  for 512x512 tiles
   int      mapbox_max_zoom = 17;
   int      mapbox_file_cache = 400000000;                                       //  400 MB                             17.04
   int      mapbox_memory_cache = 400;                                           //  400 tiles
}


void netmap_mousefunc(GtkWidget *, GdkEventButton *, void *);                    //  mouse click function for net map
void find_netmap_images(float flati, float flongi);                              //  find images at clicked position


//  menu function - choose net map source

void m_netmap_source(GtkWidget *, cchar *)
{
   using namespace netmaps;

   int  netmap_source_dialog_event(zdialog *zd, cchar *event);

   zdialog  *zd;
   int      zstat, nn;
   char     temp[200];

   F1_help_topic = "netmap_source";

/***
       ________________________________
      |          Set Map Source        |
      |                                |
      |  [_] mapnik (default)          |
      |  ----------------------------- |
      |  [x] mapbox                    |
      |  Access Key [________________] |
      |                                |
      |                [Done] [Cancel] |
      |________________________________|

***/

   zd = zdialog_new(E2X("Set Map Source"),Mwin,Bdone,Bcancel,null);
   zdialog_add_widget(zd,"hbox","hb1","dialog");
   zdialog_add_widget(zd,"check","mapnik","hb1","mapnik (default)","space=3");
   zdialog_add_widget(zd,"hsep","hsep1","dialog",0,"space=3");
   zdialog_add_widget(zd,"hbox","hb2","dialog");
   zdialog_add_widget(zd,"check","mapbox","hb2","mapbox","space=3");
   zdialog_add_widget(zd,"hbox","hb4","dialog");
   zdialog_add_widget(zd,"label","labkey","hb4","Access Key","space=3");
   zdialog_add_widget(zd,"zentry","key","hb4","","space=3|expand");

   zdialog_restore_inputs(zd);

   zdialog_set_modal(zd);                                                        //  17.08
   zdialog_run(zd,netmap_source_dialog_event,"mouse");
   zstat = zdialog_wait(zd);

   if (zstat != 1) {
      zdialog_free(zd);
      return;
   }

   zdialog_fetch(zd,"mapnik",nn);
   if (nn) netmap_source = zstrdup("mapnik");
   zdialog_fetch(zd,"mapbox",nn);
   if (nn) netmap_source = zstrdup("mapbox");

   zdialog_fetch(zd,"key",temp,200);                                             //  save key in parameters file
   mapbox_access_key = zstrdup(temp);                                            //    immediately
   save_params();
   
   if (mapwidget) gtk_widget_destroy(mapwidget);                                 //  remove prior map if any
   markerlayer = 0;
   m_load_netmap(0,0);

   zdialog_free(zd);
   return;
}


//  dialog event and completion function

int netmap_source_dialog_event(zdialog *zd, cchar *event)
{
   if (strstr("mapnik mapbox",event)) {                                          //  unset and set two checkboxes
      zdialog_stuff(zd,"mapnik",0);
      zdialog_stuff(zd,"mapbox",0);
      zdialog_stuff(zd,event,1);
   }
   
   return 1;
}


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

//  initialize for net maps

void m_load_netmap(GtkWidget *, cchar *)
{
   using namespace netmaps;

   int      yn;
   char     mapbox_total_uri[200];

   F1_help_topic = "netmap_view";

   if (Findexvalid == 0) {
      yn = zmessageYN(Mwin,Bnoindex);                                            //  no image index, offer to enable
      if (yn) index_rebuild(2,0);
      else return;
   }
   
   if (Findexvalid == 1) zmessage_post_bold(Mwin,"20/10",2,Boldindex);           //  warn, index missing new files

   if (! init_geolocs()) return;                                                 //  failed

   Ffuncbusy = 1;

   if (markerlayer) {                                                            //  refresh map markers
      netmap_paint_dots(); 
      Ffuncbusy = 0;
      return;
   }

   mapwidget = gtk_champlain_embed_new();                                        //  libchamplain map drawing area
   if (! mapwidget) goto fail;
   gtk_container_add(GTK_CONTAINER(Mvbox),mapwidget);

   mapview = gtk_champlain_embed_get_view(GTK_CHAMPLAIN_EMBED(mapwidget));
   if (! mapview) goto fail;

   if (strmatch(netmap_source,"mapnik"))                                         //  mapnik map source
   {
      map_factory = champlain_map_source_factory_dup_default();
      map_source = champlain_map_source_factory_create_cached_source(map_factory,"osm-mapnik");
      champlain_view_set_min_zoom_level(mapview,3);
   }
   
   else if (strmatch(netmap_source,"mapbox"))                                    //  mapbox map source
   {
      renderer = CHAMPLAIN_RENDERER(champlain_image_renderer_new());
      map_factory = champlain_map_source_factory_dup_default();

      strcpy(mapbox_total_uri,mapbox_access_uri);
      strcat(mapbox_total_uri,mapbox_access_key);

      tile_source = champlain_network_tile_source_new_full (
            "mapbox", "mapbox", mapbox_license_text, mapbox_license_uri, 
            mapbox_min_zoom, mapbox_max_zoom, mapbox_tile_size, 
            CHAMPLAIN_MAP_PROJECTION_MERCATOR, mapbox_total_uri, renderer);

      error_source = champlain_map_source_factory_create_error_source(map_factory,256);
      file_cache = champlain_file_cache_new_full(mapbox_file_cache, null, renderer);
      memory_cache = champlain_memory_cache_new_full(mapbox_memory_cache, renderer);

      source_chain = champlain_map_source_chain_new();
      champlain_map_source_chain_push(source_chain, error_source);
      champlain_map_source_chain_push(source_chain, CHAMPLAIN_MAP_SOURCE(tile_source));
      champlain_map_source_chain_push(source_chain, CHAMPLAIN_MAP_SOURCE(file_cache));
      champlain_map_source_chain_push(source_chain, CHAMPLAIN_MAP_SOURCE(memory_cache));

      map_source = CHAMPLAIN_MAP_SOURCE(source_chain);
   }
   
   else {
      zmessageACK(Mwin,"unknown map source: %s \n",netmap_source);
      Ffuncbusy = 0;
      return;
   }

   champlain_view_set_map_source(mapview,map_source);                            //  mapnik or mapbox

   markerlayer = champlain_marker_layer_new_full(CHAMPLAIN_SELECTION_SINGLE);
   if (! markerlayer) goto fail;
   champlain_view_add_layer(mapview,CHAMPLAIN_LAYER(markerlayer));
   champlain_marker_layer_set_selection_mode(markerlayer,CHAMPLAIN_SELECTION_NONE);
   markercolor = clutter_color_new(255,0,0,255);

   gtk_widget_add_events(mapwidget,GDK_BUTTON_PRESS_MASK);                       //  connect mouse events to net map
   G_SIGNAL(mapwidget,"button-press-event",netmap_mousefunc,0);
   G_SIGNAL(mapwidget,"button-release-event",netmap_mousefunc,0);
   G_SIGNAL(mapwidget,"motion-notify-event",netmap_mousefunc,0);

   netmap_paint_dots();                                                          //  paint map markers where images 
   Ffuncbusy = 0;
   return;

fail:
   zmessageACK(Mwin,"net/libchamplain failure");
   Ffuncbusy = 0;
   return;
}


//  paint red dots corresponding to image locations on map

void netmap_paint_dots()
{
   using namespace netmaps;

   float    flati, flongi;
   float    plati = 999, plongi = 999;

   champlain_marker_layer_remove_all(markerlayer);

   if (gallerymap)                                                               //  use gallerymap[] if present
   {                                                                             //  mark gallery images on map
      for (int ii = 0; ii < Ngallerymap; ii++)
      {
         flati = gallerymap[ii].flati;                                           //  image geocoordinates
         flongi = gallerymap[ii].flongi;
         if (flati == plati && flongi == plongi) continue;                       //  skip repititions
         plati = flati;
         plongi = flongi;
         marker[ii] = (ChamplainMarker *) champlain_point_new_full(map_dotsize,markercolor);
         champlain_location_set_location(CHAMPLAIN_LOCATION(marker[ii]),flati,flongi);
         champlain_marker_layer_add_marker(markerlayer,marker[ii]);
      }   
   }
   
   else
   {   
      for (int ii = 0; ii < Ngeolocs; ii++)                                      //  mark all images on map
      {
         flati = geolocs[ii]->flati;
         flongi = geolocs[ii]->flongi;
         marker[ii] = (ChamplainMarker *) champlain_point_new_full(map_dotsize,markercolor);
         champlain_location_set_location(CHAMPLAIN_LOCATION(marker[ii]),flati,flongi);
         champlain_marker_layer_add_marker(markerlayer,marker[ii]);
      }
   }
   
   gtk_widget_show_all(mapwidget);
   return;
}


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

//  map zoom-in on location of a selected image file

void m_netmap_zoomin(GtkWidget *, cchar *menu)
{
   using namespace netmaps;

   static char    *file = 0;
   float          flati, flongi;
   xxrec_t        *xxrec;
   
   F1_help_topic = "show_on_map";

   if (file) zfree(file);
   file = 0;

   if (clicked_file) {                                                           //  use clicked file if present
      file = clicked_file;
      clicked_file = 0;
   }
   else if (curr_file)                                                           //  else current file
      file = zstrdup(curr_file);
   else return;
   
   xxrec = get_xxrec(file);
   if (! xxrec) return;
   
   flati = xxrec->flati; 
   flongi = xxrec->flongi;
   if (flati == 0 && flongi == 0) return;

   netmap_zoomto(flati,flongi,12);   
   return;
}


//  map zoom-in on specified location with specified zoom level

void netmap_zoomto(float flati, float flongi, int zoomlev)
{
   using namespace netmaps;

   m_viewmode(0,"M");
   if (! mapview) m_load_netmap(0,0);
   champlain_view_center_on(mapview,flati,flongi);
   champlain_view_set_zoom_level(mapview,zoomlev);
   return;
}


//  get current map scale (meters/pixel) at given zoom level and geocoordinates

float netmapscale(int zoomlev, float flat, float flong)
{
   using namespace netmaps;
   float fmpp = champlain_map_source_get_meters_per_pixel(map_source,zoomlev,flat,flong);
   return fmpp;
}


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

//  Respond to mouse clicks on net map image.

void netmap_mousefunc(GtkWidget *widget, GdkEventButton *event, void *)
{
   using namespace netmaps;

   int         mx, my, px, py;
   int         ii, minii;
   int         capturedist = (map_dotsize + 2) / 2;                              //  mouse - marker capture distance
   int         Fusedot = 0;
   char        *location, *country;
   float       flati, flongi, glati, glongi;
   float       dist, mindist;
   static char *ploc = 0;
   static int  downtime;
   char        text[20];
   zdialog     *zd = zd_mapgeotags;
   
   if (! mapview) return;                                                        //  net map not available

   mx = event->x;                                                                //  mouse position in map widget
   my = event->y;
   
   flati = champlain_view_y_to_latitude(mapview,my);                             //  corresp. map coordinates
   flongi = champlain_view_x_to_longitude(mapview,mx);

   dist = mindist = 999999;
   minii = 0;

   for (ii = 0; ii < Ngeolocs; ii++)                                             //  find nearest location/country
   {
      glati = geolocs[ii]->flati;
      dist = (flati - glati) * (flati - glati);
      if (dist > mindist) continue;
      glongi = geolocs[ii]->flongi;
      dist += (flongi - glongi) * (flongi - glongi);                             //  degrees**2
      if (dist > mindist) continue;
      mindist = dist;
      minii = ii;
   }
   
   ii = minii;
   glati = geolocs[ii]->flati;                                                   //  nearest known location (dot marker)
   glongi = geolocs[ii]->flongi;
   location = geolocs[ii]->location;
   country = geolocs[ii]->country;
   
   px = champlain_view_longitude_to_x(mapview,glongi);                           //  corresp. map location
   py = champlain_view_latitude_to_y(mapview,glati);
   dist = sqrtf((px-mx) * (px-mx) + (py-my) * (py-my));                          //  distance in pixels
   if (dist <= capturedist) Fusedot = 1;                                         //  mouse is within marker dot
   
   if (event->type == GDK_BUTTON_PRESS) {
      downtime = event->time;
      return;
   }

   if (event->type == GDK_BUTTON_RELEASE)                                        //  detect button click                18.01
   {                                                                             //    press/release < 600 ms
      if (event->time - downtime > 600) return;

      if (zd)                                                                    //  stuff calling dialog
      {
         if (Fusedot) {                                                          //  click within dot
            zdialog_stuff(zd,"location",location);                               //  use nominal dot location data
            zdialog_stuff(zd,"country",country);
            zdialog_stuff(zd,"lati",glati,"%.5f");                               //  5 decimal places                   18.01
            zdialog_stuff(zd,"longi",glongi,"%.5f");
         }
         else {
            zdialog_stuff(zd,"lati",flati,"%.5f");                               //  use clicked geocoordinates only
            zdialog_stuff(zd,"longi",flongi,"%.5f");
         }
         zdialog_send_event(zd,"geomap");                                        //  activate calling dialog
         m_viewmode(0,&PFGWM);                                                   //  restore prior view mode            7.10
      }

      else if (event->button == 1 && location)                                   //  left click on marker
         find_netmap_images(flati,flongi);                                       //  show images for location 

      else if (event->button == 3) {                                             //  right click
         snprintf(text,20,"%.5f %.5f",flati,flongi);                             //  show coordinates
         poptext_mouse(text,20,-20,0.1,3);                                       //  18.07
      }
      
      return;
   }
   
   downtime = 0;                                                                 //  mouse motion

   if (location && Fusedot) {
      if (! ploc || ! strmatch(location,ploc)) {                                 //  popup the location name at mouse
         poptext_mouse(location,20,-20,0.1,1);                                   //  18.07
         ploc = location;
      }
   }

   else ploc = 0;
   
   return;
}


//  find images within the marker size, show gallery of images.
//  privat function for netmap_mousefunc(), called when a location is clicked

void find_netmap_images(float flati, float flongi)
{
   using namespace netmaps;

   int         ii, nn = 0;
   int         x1, y1, x2, y2;
   int         capturedist = (map_dotsize + 2) / 2;                              //  mouse - marker capture distance
   float       glati, glongi, grange;
   FILE        *fid;
   xxrec_t     *xxrec;
   
   x1 = champlain_view_longitude_to_x(mapview,flongi);                           //  target map pixel location
   y1 = champlain_view_latitude_to_y(mapview,flati); 

   fid = fopen(searchresults_file,"w");                                          //  open output file
   if (! fid) {
      zmessageACK(Mwin,"output file error: %s",strerror(errno));
      return;
   }
   
   if (gallerymap)                                                               //  show gallery images at location 
   {
      for (ii = 0; ii < Ngallerymap; ii++)                                       //  loop all gallery files
      {
         zmainloop(100);                                                         //  keep GTK alive
         
         glati = gallerymap[ii].flati;                                           //  image geocoordinates
         glongi = gallerymap[ii].flongi;

         x2 = champlain_view_longitude_to_x(mapview,glongi);                     //  image map pixel location
         y2 = champlain_view_latitude_to_y(mapview,glati); 
         
         grange = sqrtf((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));                      //  mouse - image pixel distance
         if (grange < 1.5 * capturedist) {                                       //  within distance limit, select
            fprintf(fid,"%s\n",gallerymap[ii].file);                             //  output matching file
            nn++;
         }
      }
   }
   
   else                                                                          //  show all images at location
   {
      for (ii = 0; ii < Nxxrec; ii++)
      {
         zmainloop(100);                                                         //  keep GTK alive

         xxrec = xxrec_tab[ii];

         glati = xxrec->flati;
         glongi = xxrec->flongi;
         if (glati == 0 && glongi == 0) continue;
         
         x2 = champlain_view_longitude_to_x(mapview,glongi);                     //  image map pixel location
         y2 = champlain_view_latitude_to_y(mapview,glati); 
         
         grange = sqrtf((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));                      //  mouse - image pixel distance
         if (grange < 1.5 * capturedist) {                                       //  within distance limit, select
            fprintf(fid,"%s\n",xxrec->file);                                     //  output matching file
            nn++;
         }
      }
   }
   
   fclose(fid); 

   if (! nn) {
      poptext_mouse(E2X("No matching images found"),10,0,0,3);
      return;
   }

   free_resources();
   navi::gallerytype = SEARCH;                                                   //  search results
   gallery(searchresults_file,"initF",0);                                        //  generate gallery of matching files
   gallery(0,"paint",0);
   m_viewmode(0,"G");

   return;
}


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

//  Save current map location (center and scale) with a given name,
//    or retrieve a previously saved map location.

namespace netmap_locs_names
{
   zdialog     *zdnetmaploc = 0;
   char        locname[60];
   double      loclati = 0, loclongi = 0;
   int         loczoom = 12;
   char        netmaplocfile[200];
   char        buff[100];
}


//  menu function

void m_netmap_locs(GtkWidget *, cchar *)                                         //  17.08
{
   using namespace netmap_locs_names;

   int   netmap_locs_dialog_event(zdialog *zd, cchar *event);
   void  netmap_locs_clickfunc(GtkWidget *, int line, int pos, int kbkey);

   zdialog     *zd;
   GtkWidget   *mtext;
   cchar       *pp;
   FILE        *fid;

   F1_help_topic = "netmap_locs";

   snprintf(netmaplocfile,200,"%s/netmap_locations",get_zhomedir());             //  net map locations file

/***
       ________________________________
      |      Net Map Locations         |
      | ______________________________ |
      ||                              ||
      || map location name 1          ||
      || long map location name 2     ||     scrolling window
      || map location name 3          ||
      ||  ...                         ||
      ||______________________________||
      |                                |
      | map location: [______________] |     text entry for location name
      |                                |
      |          [add] [delete] [done] |
      |________________________________|
      

      [location]     empty until filled-in or a location from the list is clicked
      [add]          current location is added to list or replaced 
      [delete]       current location is deleted from list
      
      location position and scale is from current map location
      location list is kept in alphabetic order
      
***/

   if (zdnetmaploc) return;                                                      //  already active

   zd = zdialog_new(E2X("Net Map Locations"),Mwin,Badd,Bdelete,Bdone,null);
   zdnetmaploc = zd;
   zdialog_add_widget(zd,"frame","frlocs","dialog",0,"expand");
   zdialog_add_widget(zd,"scrwin","scrlocs","frlocs",0,"expand");
   zdialog_add_widget(zd,"text","mtext","scrlocs");
   zdialog_add_widget(zd,"hbox","hbvn","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labvn","hbvn",E2X("map location:"),"space=3");
   zdialog_add_widget(zd,"zentry","locname","hbvn","","space=3");
   
   zdialog_resize(zd,200,300);
   zdialog_run(zd,netmap_locs_dialog_event,"parent");

   mtext = zdialog_widget(zd,"mtext");                                           //  map location list in dialog
   textwidget_clear(mtext);

   fid = fopen(netmaplocfile,"r");                                               //  map location list file
   if (fid) {
      while (true) {
         pp = fgets_trim(buff,100,fid,1);                                        //  read location | lati | longi | zoom
         if (! pp) break;
         pp = strField(buff,'|',1);                                              //  isolate location
         if (! pp) continue;
         if (strlen(pp) < 2) continue;
         textwidget_append(mtext,0,"%s \n",pp);                                  //  write into dialog list
      }
      fclose(fid);
   }

   textwidget_set_callbackfunc(mtext,netmap_locs_clickfunc);                     //  connect click function
   return;
}


//  dialog event and completion callback function

int netmap_locs_dialog_event(zdialog *zd, cchar *event)
{
   using namespace netmaps;
   using namespace netmap_locs_names;
   
   int         ff, nn;
   cchar       *pp, *pp2;
   GtkWidget   *mtext;
   FILE        *fidr;
   
   if (! zd->zstat) return 1;                                                    //  wait for completion
   
   if (zd->zstat == 1)                                                           //  [add] new map location record
   {
      zd->zstat = 0;                                                             //  keep dialog active

      zdialog_fetch(zd,"locname",locname,60);
      if (strTrim2(locname) < 2) {
         zmessageACK(Mwin,E2X("supply a reasonable name"));
         return 1;
      }
      
      loclati = champlain_view_get_center_latitude(mapview);                     //  get current map location
      loclongi = champlain_view_get_center_longitude(mapview);
      loczoom = champlain_view_get_zoom_level(mapview);
      
      snprintf(buff,100,"%s|%.4f|%.4f|%d",locname,loclati,loclongi,loczoom);     //  prepare new location rec.

      linedit_open(netmaplocfile);                                               //  17.08
      
      ff = 0;

      while (true)                                                               //  read next location record
      {
         pp = linedit_get();
         if (! pp) break;
         nn = strcasecmp(locname,pp);                                            //  compare new location with location record
         if (! ff && nn < 0) {                                                   //  new location < location record
            linedit_put(buff);
            ff = 1;
         }
         linedit_put(pp);                                                        //  write location record
      }
      
      if (! ff) linedit_put(buff);                                               //  insert new location last

      linedit_close();
      goto update_dialog;
   }

   if (zd->zstat == 2)                                                           //  [delete] selected map location record
   {
      zd->zstat = 0;                                                             //  keep dialog active

      zdialog_fetch(zd,"locname",locname,60);
      
      linedit_open(netmaplocfile);                                               //  17.08
      
      while (true)                                                               //  read next location record
      {
         pp = linedit_get();
         if (! pp) break;
         pp2 = strField(pp,'|',1);                                               //  get location name
         if (! pp2) continue;
         if (strmatch(locname,pp2)) continue;                                    //  omit deleted location
         linedit_put(pp);                                                        //  write location record
      }
      
      linedit_close();
      goto update_dialog;
   }

   zdialog_destroy(zd);                                                          //  [done] or [x]
   zdnetmaploc = 0;
   return 1;

update_dialog:

   mtext = zdialog_widget(zd,"mtext");                                           //  map location name list in dialog
   textwidget_clear(mtext);                                                      //  clear list

   fidr = fopen(netmaplocfile,"r");                                              //  update dialog list from file
   if (! fidr) return 1;

   while (true) {
      pp = fgets_trim(buff,100,fidr,1);                                          //  read location | lati | longi | zoom
      if (! pp) break;
      pp = strField(buff,'|',1);                                                 //  isolate location
      if (! pp) continue;
      if (strlen(pp) < 2) continue;
      textwidget_append2(mtext,0,"%s \n",pp);                                    //  write into dialog list
   }
   fclose(fidr);

   return 1;
}      


//  get clicked location name and set corresponding map location and zoom level

void netmap_locs_clickfunc(GtkWidget *widget, int line, int pos, int kbkey)
{
   using namespace netmap_locs_names;

   cchar    *pp1, *pp2;
   FILE     *fidr;
   zdialog  *zd = zdnetmaploc;
   
   if (! zd) return;
   
   if (kbkey == GDK_KEY_F1) {                                                    //  key F1 pressed, show help          18.01
      showz_userguide(F1_help_topic);
      return;
   }

   pp1 = textwidget_line(widget,line,1);                                         //  get clicked line, highlight
   if (! pp1 || ! *pp1) return;
   textwidget_highlight_line(widget,line);

   strTrim2(locname,pp1);
   zdialog_stuff(zd,"locname",locname);

   fidr = fopen(netmaplocfile,"r");                                              //  open/read netmap locs file 
   if (! fidr) {
      zmessageACK(Mwin,strerror(errno));
      return;
   }
   
   while (true)                                                                  //  read next location record
   {
      pp2 = fgets_trim(buff,100,fidr);
      if (! pp2) break;
      pp2 = strField(buff,'|',1);
      if (strmatch(locname,pp2)) break;                                          //  found matching record
   }
   
   fclose(fidr);
   if (! pp2 || ! strmatch(locname,pp2)) goto notfound;

   loclati = loclongi = loczoom = 0;

   pp1 = strField(buff,'|',2);                                                   //  get map location data from record
   if (! pp1) goto baddata;
   loclati = atof(pp1);
   if (loclati <= -90 || loclati >= +90) goto baddata;

   pp1 = strField(buff,'|',3);
   if (! pp1) goto baddata;
   loclongi = atof(pp1);
   if (loclongi <= -180 || loclongi >= +180) goto baddata;

   pp1 = strField(buff,'|',4);
   if (! pp1) goto baddata;
   loczoom = atoi(pp1);
   if (loczoom < 1 || loczoom > 20) goto baddata;
   
   netmap_zoomto(loclati,loclongi,loczoom);                                      //  set this map location
   return;

notfound:
   printz("net map location not found: %s \n",locname);
   return;
   
baddata:
   printz("net map location invalid: %s %.4f %.4f %d \n",
                  locname,loclati,loclongi,loczoom);
   return;
}


/********************************************************************************
   Functions to read and write exif/iptc or other metadata
*********************************************************************************/

//  get EXIF/IPTC metadata for given image file and EXIF/IPTC key(s)
//  returns array of pointers to corresponding key values
//  if a key is missing, corresponding pointer is null
//  returned strings belong to caller, are subject for zfree()
//  up to 100 keynames may be requested per call
//  returns: 0 = OK, +N = error

int exif_get(cchar *file, cchar **keys, char **kdata, int nkeys)
{
   char        *pp, geostring[20];
   char        *inputs[120], *outputs[100];                                      //  higher limits                      18.01
   int         cc, ii, jj, err;
   float       geofloat;
   uint        ucc;
   
   if (nkeys < 1 || nkeys > 99) zappcrash("exif_get nkeys: %d",nkeys);

   cc = nkeys * sizeof(char *);                                                  //  clear outputs
   memset(kdata,0,cc);

   inputs[0] = (char *) "-m";                                                    //  options for exiftool
   inputs[1] = (char *) "-s2";
   inputs[2] = (char *) "-n";
   inputs[3] = (char *) "-fast";                                                 //  -fast2 loses maker notes
   jj = 4;

   for (ii = 0; ii < nkeys; ii++)                                                //  build exiftool inputs
   {
      cc = strlen(keys[ii]);                                                     //  -keyname
      if (! cc) {
         printz("exif_get() null key \n");                                       //  bugfix                             17.04
         return 1;
      }
      inputs[jj] = (char *) zmalloc(cc+2);
      inputs[jj][0] = '-';
      strcpy(inputs[jj]+1,keys[ii]);
      if (strmatchcase(keys[ii],"location"))                                     //  make "location" = "city"
         strcpy(inputs[jj]+1,"city"); 
      jj++;
   }

   inputs[jj] = zstrdup(file);                                                   //  filename last
   jj++;

   err = exif_server(jj,inputs,outputs);                                         //  get exif outputs
   if (err) return 1;                                                            //  exif_server() failure

   for (ii = 4; ii < jj; ii++)                                                   //  free memory
      zfree(inputs[ii]);

   for (ii = 0; ii < nkeys; ii++)                                                //  search outputs
   {
      pp = outputs[ii];                                                          //  keyname: keyvalue
      if (! pp) break;

      for (jj = 0; jj < nkeys; jj++)
      {
         if (strmatchcase(keys[jj],"location")) {                                //  "location" comes back "city"
            if (! strmatchcaseN(pp,"city",4)) continue;
            if (strlen(pp) > 6) kdata[jj] = zstrdup(pp+6);
         }
         else if (strmatchN(keys[jj],"GPSLatitude",11)) {                        //  round to 5 decimal places          18.01
            if (! strmatchN(pp,"GPSLatitude",11)) continue;
            err = convSF(pp+13,geofloat);
            if (err > 1) continue;
            snprintf(geostring,20,"%.5f",geofloat);
            kdata[jj] = zstrdup(geostring);
         }
         else if (strmatchN(keys[jj],"GPSLongitude",12)) {                       //  round to 5 decimal places          18.01
            if (! strmatchN(pp,"GPSLongitude",12)) continue;
            err = convSF(pp+14,geofloat);
            if (err > 1) continue;
            snprintf(geostring,20,"%.5f",geofloat);
            kdata[jj] = zstrdup(geostring);
         }
         else {
            ucc = strlen(keys[jj]);                                              //  look for matching input keyname
            if (! strmatchcaseN(pp,keys[jj],ucc)) continue;
            if (strlen(pp) > ucc+2) kdata[jj] = zstrdup(pp+ucc+2);
         }
      }
      
      zfree(pp);
   }

   return 0;
}


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

//  create or change EXIF/IPTC metadata for given image file and key(s)
//
//  command:
//    exiftool -m -overwrite_original -keyname="keyvalue" ... "file"
//
//  NOTE: exiftool replaces \n (newline) in keyvalue with . (period).

int exif_put(cchar *file, cchar **keys, cchar **kdata, int nkeys)
{
   int      ii, jj, cc;
   char     *inputs[40];

   if (nkeys < 1 || nkeys > 30) zappcrash("exif_put nkeys: %d",nkeys);           //  higher limit                       18.01

   inputs[0] = (char *) "-m";                                                    //  exiftool options
   inputs[1] = (char *) "-overwrite_original";                                   //  -P preserve date removed
   jj = 2;

   for (ii = 0; ii < nkeys; ii++)                                                //  build exiftool inputs
   {
      if (! kdata[ii]) continue;                                                 //  skip missing data    bugfix        17.04.3
      cc = strlen(keys[ii]) + strlen(kdata[ii]) + 3;
      inputs[jj] = (char *) zmalloc(cc);
      inputs[jj][0] = '-';                                                       //  -keyname=value

      if (strmatchcase(keys[ii],"location")) {                                   //  make "location" = "city"
         strcpy(inputs[jj]+1,"city");
         cc = 4;
      }
      else {
         strcpy(inputs[jj]+1,keys[ii]);
         cc = strlen(keys[ii]);
      }

      inputs[jj][cc+1] = '=';
      strcpy(inputs[jj]+cc+2,kdata[ii]);
      jj++;

      if (strmatchcase(keys[ii],"GPSLatitude")) {                                //  take care of latitude N/S
         if (*kdata[ii] == '-')
            inputs[jj] = zstrdup("-GPSLatitudeRef=S");
         else
            inputs[jj] = zstrdup("-GPSLatitudeRef=N");
         jj++;
      }

      if (strmatchcase(keys[ii],"GPSLongitude")) {                               //  and longitude E/W
         if (*kdata[ii] == '-')
            inputs[jj] = zstrdup("-GPSLongitudeRef=W");
         else
            inputs[jj] = zstrdup("-GPSLongitudeRef=E");
         jj++;
      }
   }

   inputs[jj] = zstrdup(file);                                                   //  last input is filename
   jj++;

   exif_server(jj,inputs,0);                                                     //  outputs discarded

   for (ii = 2; ii < jj; ii++)                                                   //  free memory
       zfree(inputs[ii]);

   return 0;
}


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

//  copy EXIF/IPTC data from one image file to new (edited) image file
//  if nkeys > 0: added keys[] to be replaced with new values kdata[]
//  exiftool -m -tagsfromfile file1 -all -xmp -iptc -icc_profile 
//                 [-keyname=newvalue ...]  file2 -overwrite_original

int exif_copy(cchar *file1, cchar *file2, cchar **keys, cchar **kdata, int nkeys)
{
   char     *inputs[40];                                                         //  revised
   int      cc, ii, jj, nfixed;

   if (nkeys > 30) zappcrash("exif_copy() nkeys %d",nkeys);                      //  higher limit                       18.01

   inputs[0] = (char *) "-m";                                                    //  -m               (suppress warnings)
   inputs[1] = (char *) "-tagsfromfile";                                         //  -tagsfromfile
   inputs[2] = zstrdup(file1);                                                   //  file1
   inputs[3] = (char *) "-all";                                                  //  -all
   inputs[4] = (char *) "-xmp";                                                  //  -xmp
   inputs[5] = (char *) "-iptc";                                                 //  -iptc
   inputs[6] = (char *) "-icc_profile";                                          //  -icc_profile

   nfixed = jj = 7;                                                              //  no. fixed inputs

   for (int ii = 0; ii < nkeys; ii++)                                            //  -keyname=keyvalue
   {
      if (! kdata[ii]) continue;                                                 //  skip missing data   bugfix         17.04.3
      cc = strlen(keys[ii]) + strlen(kdata[ii]) + 3;
      inputs[jj] = (char *) zmalloc(cc);
      *inputs[jj] = 0;
      strncatv(inputs[jj],cc,"-",keys[ii],"=",kdata[ii],null);
      jj++;
   }

   inputs[jj++] = zstrdup(file2);                                                //  file2
   inputs[jj++] = (char *) "-overwrite_original";                                //  -overwrite_original

   exif_server(jj,inputs,0);

   zfree(inputs[2]);                                                             //  free memory
   for (ii = nfixed; ii < nfixed+nkeys; ii++)
   zfree(inputs[ii]);

   return 0;
}


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

   int exif_server(int Nrecs, char **inputs, char **outputs)

   Server wrapper for exiftool for put/get exif/iptc data.
   This saves perl startup overhead for each call (0.1 >> 0.01 secs).

   Input records: -opt1
                  -opt2
                    ...
                  -keyword1=value1
                  -keyword2=value2
                    ...
                  filename.jpg
                  (null pointer)

   Returned: list of pointers to resulting output records.
   There are <= Nrecs outputs corresponding to keyword inputs.
   These are formatted keyword: text-string-value.
   If < Nrecs output, unused outputs are null pointers.
   These are subject to zfree().
   If outputs = null, outputs are discarded.

   Returns 0 if OK, +N if error.

   First call:
      Starts exiftool with pipe input and output files.
   Subsequent calls:
      The existing exiftool process is re-used so that the
      substantial startup overhead is avoided.
   To kill the exiftool process: exif_server(0,0,0).
   
   There are two servers which can run parallel if called by two threads.
   
   The exiftool perl process has a significant memory leak that can reach        //  bugfix  18.01
   gigabytes if Fotoxx image index function must process 100K files or more. 
   Solution: exit perl process after 1000 calls and start over with next call.

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

int exif_server(int Nrecs, char **inputs, char **outputs)
{
   int exif_server1(int Nrecs, char **inputs, char **outputs);                   //  2 parallel server processes
   int exif_server2(int Nrecs, char **inputs, char **outputs);

   static int  busy1 = 0, busy2 = 0;
   double      time0, time1;
   int         err;
   
   if (! Nrecs) {
      printz("stop EXIF servers \n");
      zmainsleep(0.5);
      exif_server1(0,0,0);
      exif_server2(0,0,0);
      return 0;
   }

   time0 = get_seconds();

   while (true)
   {
      if (resource_lock(busy1)) {                                                //  use resource locks                 18.01
         err = exif_server1(Nrecs,inputs,outputs);
         resource_unlock(busy1);
         return err;
      }
      
      if (resource_lock(busy2)) {
         err = exif_server2(Nrecs,inputs,outputs);
         resource_unlock(busy2);
         return err;
      }
      
      time1 = get_seconds();
      if (time1 - time0 > 2) break;
      zsleep(0.001);
   }
   
   printz("exiftool (perl) is not responding");
   exit(0);
}


int exif_server1(int Nrecs, char **inputs, char **outputs)                       //  exiftool process 1
{
   static int   fcf = 1;                                                         //  first call flag
   static int   Ncalls = 0;
   static FILE  *fid1 = 0, *fid2 = 0;                                            //  exiftool input, output files
   static char  input_file[100] = "";
   int          ii, cc, err;
   char         *pp, command[100];
   char         outrec[exif_maxcc];                                              //  single output record

   if (! Nrecs)                                                                  //  kill exiftool if requested
   {
      if (fcf) return 0;                                                         //  never started
      fid1 = fopen(input_file,"a");
      if (fid1) {
         fprintf(fid1,"-stay_open\nFalse\n");                                    //  tell it to exit
         fclose(fid1);
      }

      if (fid2) pclose(fid2);
      fcf = 1;                                                                   //  restart if called again
      return 0;
   }

   if (fcf)                                                                      //  first call only
   {
      snprintf(input_file,100,"%s/exiftool_input1",temp_dirk);                   //  only difference in serverN         NOTE

      fid1 = fopen(input_file,"w");                                              //  start exiftool input file
      if (! fid1) {
         zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
         return 1;
      }

      snprintf(command,100,"exiftool -stay_open True -@ %s; exit",input_file);   //  exit shell when exit exiftool      18.01

      fid2 = popen(command,"r");                                                 //  start exiftool and output file
      if (! fid2) {
         zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
         fclose(fid1);
         return 2;
      }
      
      fcf = 0;
      Ncalls = 0;
   }
   
   Ncalls++;                                                                     //  count calls                        18.01

   for (ii = 0; ii < Nrecs; ii++)
      fprintf(fid1,"%s\n",inputs[ii]);                                           //  write to exiftool, 1 per record

   err = fprintf(fid1,"-execute\n");                                             //  tell exiftool to process
   if (err < 0) {
      zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
      return 3;
   }

   fflush(fid1);                                                                 //  flush buffer

   if (outputs) {
      cc = Nrecs * sizeof(char *);                                               //  clear outputs
      memset(outputs,0,cc);
   }

   for (ii = 0; ii < 99; ii++)                                                   //  get ALL exiftool outputs
   {
      pp = fgets_trim(outrec,exif_maxcc,fid2,1);
      if (! pp) break;
      if (strncmp(outrec,"{ready}",7) == 0) break;                               //  look for output end
      if (outputs && ii < Nrecs)
         outputs[ii] = zstrdup(outrec);                                          //  add to returned records
   }

   return 0;
}


int exif_server2(int Nrecs, char **inputs, char **outputs)                       //  exiftool process 2
{
   static int   fcf = 1;                                                         //  first call flag
   static int   Ncalls = 0;
   static FILE  *fid1 = 0, *fid2 = 0;                                            //  exiftool input, output files
   static char  input_file[100] = "";
   int          ii, cc, err;
   char         *pp, command[100];
   char         outrec[exif_maxcc];                                              //  single output record

   if (! Nrecs)                                                                  //  kill exiftool if requested
   {
      if (fcf) return 0;                                                         //  never started
      fid1 = fopen(input_file,"a");
      if (fid1) {
         fprintf(fid1,"-stay_open\nFalse\n");                                    //  tell it to exit
         fclose(fid1);
      }

      if (fid2) pclose(fid2);
      fcf = 1;                                                                   //  restart if called again
      return 0;
   }

   if (fcf)                                                                      //  first call only
   {
      snprintf(input_file,100,"%s/exiftool_input2",temp_dirk);                   //  only difference in serverN         NOTE

      fid1 = fopen(input_file,"w");                                              //  start exiftool input file
      if (! fid1) {
         zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
         return 1;
      }

      snprintf(command,100,"exiftool -stay_open True -@ %s; exit",input_file);   //  exit shell when exit exiftool      18.01

      fid2 = popen(command,"r");                                                 //  start exiftool and output file
      if (! fid2) {
         zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
         fclose(fid1);
         return 2;
      }
      
      fcf = 0;
      Ncalls = 0;
   }
   
   Ncalls++;                                                                     //  count calls                        18.01

   for (ii = 0; ii < Nrecs; ii++)
      fprintf(fid1,"%s\n",inputs[ii]);                                           //  write to exiftool, 1 per record

   err = fprintf(fid1,"-execute\n");                                             //  tell exiftool to process
   if (err < 0) {
      zmessageACK(Mwin,"exif_server: %s \n",strerror(errno));
      return 3;
   }

   fflush(fid1);                                                                 //  flush buffer

   if (outputs) {
      cc = Nrecs * sizeof(char *);                                               //  clear outputs
      memset(outputs,0,cc);
   }

   for (ii = 0; ii < 99; ii++)                                                   //  get ALL exiftool outputs
   {
      pp = fgets_trim(outrec,exif_maxcc,fid2,1);
      if (! pp) break;
      if (strncmp(outrec,"{ready}",7) == 0) break;                               //  look for output end
      if (outputs && ii < Nrecs)
         outputs[ii] = zstrdup(outrec);                                          //  add to returned records
   }

   return 0;
}


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

//  convert between EXIF and fotoxx tag date formats
//  EXIF date: yyyy:mm:dd hh:mm:ss        20 chars.
//  tag date: yyyymmddhhmmss              16 chars.
//

void exif_tagdate(cchar *exifdate, char *tagdate)
{
   int      cc;

   memset(tagdate,0,15);
   cc = strlen(exifdate);

   if (cc > 3) strncpy(tagdate+0,exifdate+0,4);
   if (cc > 6) strncpy(tagdate+4,exifdate+5,2);
   if (cc > 9) strncpy(tagdate+6,exifdate+8,2);
   if (cc > 12) strncpy(tagdate+8,exifdate+11,2);
   if (cc > 15) strncpy(tagdate+10,exifdate+14,2);
   if (cc > 18) strncpy(tagdate+12,exifdate+17,2);
   tagdate[14] = 0;
   return;
}

void tag_exifdate(cchar *tagdate, char *exifdate)
{
   int      cc;

   memset(exifdate,0,20);
   cc = strlen(tagdate);

   strcpy(exifdate,"1900:01:01 00:00:00");
   if (cc > 3) strncpy(exifdate+0,tagdate+0,4);
   if (cc > 5) strncpy(exifdate+5,tagdate+4,2);
   if (cc > 7) strncpy(exifdate+8,tagdate+6,2);
   if (cc > 9) strncpy(exifdate+11,tagdate+8,2);
   if (cc > 11) strncpy(exifdate+14,tagdate+10,2);
   if (cc > 13) strncpy(exifdate+17,tagdate+12,2);
   exifdate[19] = 0;
   return;
}


/********************************************************************************
   Functions to read and write image index file on disk
   and update the image index memory table (xxrec table).
*********************************************************************************/

//  Get the image index record for the given image file.
//  Returns pointer to xxrec or null if not found.
//  Returned xxrec fields are NOT subjects for zfree()

xxrec_t * get_xxrec(cchar *file)
{
   int      ii, jj, kk, rkk, last;
   
   if (! file || *file != '/') return 0;
   if (! Findexvalid) return 0;                                                  //  index not valid
   if (! Nxxrec) return 0;                                                       //  no data

   ii = Nxxrec / 2;                                                              //  next table entry to search
   jj = (ii + 1) / 2;                                                            //  next increment
   last = Nxxrec - 1;                                                            //  last entry
   rkk = 0;

   while (true)                                                                  //  binary search 
   {
      kk = strcmp(xxrec_tab[ii]->file,file);                                     //  compare table entry to file

      if (kk > 0) {
         ii -= jj;                                                               //  too high, go back in table
         if (ii < 0) break;
      }

      else if (kk < 0) {
         ii += jj;                                                               //  too low, go forward in table
         if (ii > last) break;
      }

      else return xxrec_tab[ii];                                                 //  matched - return xxrec

      jj = jj / 2;                                                               //  reduce increment

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


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

//  minimized version of get_xxrec() for use by gallery window.
//  fdate[16] pdate[16] wwhh[16] fsize[16] provided by caller for returned data.
//  returns 0 if found, 1 if not (get_xxrec() diagnoses)

int get_xxrec_min(cchar *file, char *fdate, char *pdate, char *wwhh, char *fsize)
{
   xxrec_t  *xxrec;
   
   xxrec = get_xxrec(file);
   if (! xxrec) {
      strcpy(fdate,"null");
      strcpy(pdate,"null");
      strcpy(wwhh,"null");
      strcpy(fsize,"null");
      return 1;
   }

   strncpy0(fdate,xxrec->fdate,15);
   strncpy0(pdate,xxrec->pdate,15);
   strncpy0(wwhh,xxrec->wwhh,15);
   strncpy0(fsize,xxrec->fsize,15);                                              //  18.07
   return 0;
}


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

//  Add or update the image index record for the given image file.
//  If xxrec is null, delete the table entry for the file.
//  Append new index record data to the image index file on disk.
//  (previous record, if any, is now superceeded but still present)
//  Return 0 if success, +N if error (diagnosed).

int put_xxrec(xxrec_t *xxrec, cchar *file)
{
   char        indexfile[200];
   int         ii, iix, nn, err;
   int         Finsert, Fdelete, Freplace, Fdone;
   float       fsize;
   xxrec_t     *xxrec_old, *xxrec_new = 0;
   FILE        *fid;
   STATB       statb;
   
   if (! file || *file != '/') {
      zmessageACK(Mwin,"put_xxrec() file: %s",file);
      return 0;
   }
   
   if (! Findexvalid) return 1;                                                  //  image index not valid
   if (! Nxxrec) return 1;                                                       //  no data
   
   if (xxrec) {
      err = stat(file,&statb);                                                   //  check image file exists
      if (err || ! S_ISREG(statb.st_mode)) {
         zmessageACK(Mwin,"file %s not found \n",file);
         return 0;
      }
      fsize = statb.st_size / FMEGA;                                             //  18.07
   }

   xxrec_old = get_xxrec(file);                                                  //  old image index record, if any

   if (! xxrec && ! xxrec_old) return 0;                                         //  nothing to do

   Finsert = Fdelete = Freplace = Fdone = 0;
   if (! xxrec && xxrec_old) Fdelete = 1;                                        //  delete old record
   if (xxrec && ! xxrec_old) Finsert = 1;                                        //  insert new record
   if (xxrec && xxrec_old) Freplace = 1;                                         //  replace old record
   
   if (Finsert || Freplace)
   {
      xxrec_new = (xxrec_t *) zmalloc(sizeof(xxrec_t));                          //  make new xxrec with data from caller
      memset(xxrec_new,0,sizeof(xxrec_t));

      xxrec_new->file = zstrdup(file);
   
      compact_time(statb.st_mtime,xxrec_new->fdate);                             //  refresh file mod date/time
   
      if (xxrec->pdate[0]) strcpy(xxrec_new->pdate,xxrec->pdate);
      else strcpy(xxrec_new->pdate,"null");

      if (xxrec->wwhh[0]) strcpy(xxrec_new->wwhh,xxrec->wwhh);
      else strcpy(xxrec_new->wwhh,"null");

      if (xxrec->fsize[0]) strcpy(xxrec_new->fsize,xxrec->fsize);                //  18.07
      else strcpy(xxrec_new->fsize,"null");

      if (xxrec->rating[0]) strcpy(xxrec_new->rating,xxrec->rating);
      else strcpy(xxrec_new->rating,"0");
      
      if (xxrec->tags) xxrec_new->tags = zstrdup(xxrec->tags);
      else xxrec_new->tags = zstrdup("null");

      if (xxrec->capt) xxrec_new->capt = zstrdup(xxrec->capt);
      else xxrec_new->capt = zstrdup("null");

      if (xxrec->comms) xxrec_new->comms = zstrdup(xxrec->comms);
      else xxrec_new->comms = zstrdup("null");

      xxrec_new->location = zstrdup(xxrec->location); 
      xxrec_new->country = zstrdup(xxrec->country);
      xxrec_new->flati = xxrec->flati;
      xxrec_new->flongi = xxrec->flongi;
      xxrec_new->xmeta = xxrec->xmeta;                                           //  18.01
   }

   iix = -1;   

   for (ii = 0; ii < Nxxrec; ii++)                                               //  find target position in table
   {
      nn = strcmp(file,xxrec_tab[ii]->file);

      if (nn > 0) continue;
      if (nn == 0) {
         if (Finsert) goto badbug;                                               //  insert duplicate
         iix = ii;                                                               //  entry to delete or replace
         break;
      }
      if (nn < 0) {
         if (Fdelete || Freplace) goto badbug;                                   //  not found
         iix = ii;                                                               //  place to insert new entry
         break;                                                                  //  (current entry will be next)
      }
   }
   
   if (iix < 0 && (Fdelete || Freplace)) goto badbug;                            //  not found
   if (iix < 0) iix = Nxxrec;                                                    //  add to end of table

   if (Nxxrec == maximages) {
      zmessageACK(Mwin,"exceed %d max files, cannot continue",maximages);
      quitxx();
   }

   if (Finsert)
   {
      for (ii = Nxxrec; ii > iix; ii--)                                          //  make empty slo1
         xxrec_tab[ii] = xxrec_tab[ii-1];
      xxrec_tab[iix] = xxrec_new;                                                //  insert new entry
      Nxxrec++;
   }

   if (Fdelete) 
   {
      zfree(xxrec_tab[iix]->file);                                               //  delete old entry
      zfree(xxrec_tab[iix]->tags);
      zfree(xxrec_tab[iix]->capt);
      zfree(xxrec_tab[iix]->comms);
      zfree(xxrec_tab[iix]->location); 
      zfree(xxrec_tab[iix]->country);
      zfree(xxrec_tab[iix]->xmeta);
      zfree(xxrec_tab[iix]);                                                     //  18.01
      Nxxrec--;
      for (ii = iix; ii < Nxxrec; ii++)                                          //  pack down
         xxrec_tab[ii] = xxrec_tab[ii+1];
   }

   if (Freplace) 
   {
      zfree(xxrec_tab[iix]->file);                                               //  replace old entry
      zfree(xxrec_tab[iix]->tags);
      zfree(xxrec_tab[iix]->capt);
      zfree(xxrec_tab[iix]->comms);
      zfree(xxrec_tab[iix]->location); 
      zfree(xxrec_tab[iix]->country);
      zfree(xxrec_tab[iix]->xmeta);                                              //  18.01
      zfree(xxrec_tab[iix]);
      xxrec_tab[iix] = xxrec_new;                                                //  replace with new entry
   }

   if (Finsert || Freplace)
   {
      snprintf(indexfile,200,"%s/indexC",index_dirk);
      fid = fopen(indexfile,"a");                                                //  append new record to image index file
      if (! fid) goto file_err;

      nn = fprintf(fid,"file: %s\n",file);                                       //  file path name
      if (! nn) goto file_err;

      nn = fprintf(fid,"date: %s  %s\n",xxrec_new->pdate,xxrec_new->fdate);      //  photo and file date record
      if (! nn) goto file_err;

      nn = fprintf(fid,"size: %s  %.2f\n",xxrec_new->wwhh,fsize);                //  size record, 12345x2345  12.34
      if (! nn) goto file_err;

      nn = fprintf(fid,"stars: %s\n",xxrec_new->rating);                         //  rating record
      if (! nn) goto file_err;

      nn = fprintf(fid,"tags: %s\n",xxrec_new->tags);                            //  tags record
      if (! nn) goto file_err;

      nn = fprintf(fid,"capt: %s\n",xxrec_new->capt);                            //  caption record
      if (! nn) goto file_err;

      nn = fprintf(fid,"comms: %s\n",xxrec_new->comms);                          //  comments record
      if (! nn) goto file_err;

      nn = fprintf(fid,"gtags: %s^ %s^ %.4f^ %.4f\n",
            xxrec_new->location, xxrec_new->country, 
            xxrec_new->flati, xxrec_new->flongi);
      if (! nn) goto file_err;
      
      nn = fprintf(fid,"xmeta: %s\n",xxrec_new->xmeta);                          //  18.01
      if (! nn) goto file_err;

      nn = fprintf(fid,"END\n");                                                 //  EOL  18.01
      if (! nn) goto file_err;

      err = fclose(fid);
      if (err) goto file_err;
   }
   
   return 0;

file_err:
   zmessageACK(Mwin,"image index write error\n %s",strerror(errno));
   if (fid) fclose(fid);
   fid = 0;
   return 3;

badbug:
   zmessageACK(Mwin,"bug in put_xxrec() \n %s",file);
   return 4;
}


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

//  Read image index files sequentially, return one index record per call.
//  Set ftf = 1 for first read, will be reset to 0.
//  Returns xxrec or null for EOF or error.
//  Returned xxrec_t and its allocated pointers are subject to zfree().
//  Used by index_rebuild() function.

xxrec_t * read_xxrec_seq(int &ftf)
{
   xxrec_t        *xxrec = 0;
   char           indexfile[200];
   static FILE    *fid = 0;
   static char    buff[indexrecl];
   cchar          *pp, *pp2;
   float          flati, flongi;
   
   if (ftf)                                                                      //  initial call
   {
      ftf = 0;
      snprintf(indexfile,200,"%s/indexC",index_dirk);
      fid = fopen(indexfile,"r");
      if (! fid) return 0;                                                       //  no index file ?
      *buff = 0;                                                                 //  insure no leftover data
   }

   while (true)                                                                  //  read to next "file: " record       18.01
   {
      pp = fgets_trim(buff,indexrecl,fid);
      if (! pp) {
         fclose(fid);                                                            //  EOF
         return 0;
      }
      if (strmatchN(pp,"file: ",6)) break;
   }

   xxrec = (xxrec_t *) zmalloc(sizeof(xxrec_t));                                 //  allocate returned xxrec
   memset(xxrec,0,sizeof(xxrec_t));

   xxrec->file = zstrdup(buff+6);                                                //  image file name

   while (true)                                                                  //  get recs following "file" record
   {
      pp = fgets_trim(buff,indexrecl,fid);
      if (! pp) break;
      
      if (strmatchN(pp,"END",3)) break;                                          //  end of recs for this file          18.01

      else if (strmatchN(pp,"date: ",6)) {
         pp += 6;
         pp2 = strField(pp,' ',1);                                               //  EXIF (photo) date, yyyymmddhhmmss
         if (pp2) strncpy0(xxrec->pdate,pp2,15);
         pp2 = strField(pp,' ',2);
         if (pp2) strncpy0(xxrec->fdate,pp2,15);                                 //  file mod date, yyyymmddhhmmss
      }

      else if (strmatchN(pp,"stars: ",7)) {                                      //  rating, "0" to "5" stars
         xxrec->rating[0] = *(pp+7);
         xxrec->rating[1] = 0;
      }

      else if (strmatchN(pp,"size: ",6)) {                                       //  size, "12345x2345  12.34"          18.07
         pp += 6;
         pp2 = strField(pp,' ',1);
         if (pp2) strncpy0(xxrec->wwhh,pp2,15);
         pp2 = strField(pp,' ',2);
         if (pp2) strncpy0(xxrec->fsize,pp2,15);
      }

      else if (strmatchN(pp,"tags: ",6))                                         //  tags
         xxrec->tags = zstrdup(pp+6);

      else if (strmatchN(pp,"capt: ",6))                                         //  caption
         xxrec->capt = zstrdup(pp+6);

      else if (strmatchN(pp,"comms: ",7))                                        //  comments
         xxrec->comms = zstrdup(pp+7);

      else if (strmatchN(pp,"gtags: ",7)) {                                      //  geotags
         pp += 7;
         pp2 = strField(pp,"^",1);
         if (pp2) xxrec->location = zstrdup(pp2);
         else xxrec->location = zstrdup("null");
         pp2 = strField(pp,"^",2);
         if (pp2) xxrec->country = zstrdup(pp2);
         else xxrec->country = zstrdup("null");
         flati = flongi = 999;
         pp2 = strField(pp,"^",3);
         if (pp2) flati = atof(pp2);
         pp2 = strField(pp,"^",4);
         if (pp2) flongi = atof(pp2);
         if (strmatch(xxrec->location,"null")) flati = flongi = 0;
         if (strmatch(xxrec->country,"null")) flati = flongi = 0;
         if (flati < -90.0 || flati > 90.0) flati = flongi = 0;
         if (flongi < -180.0 || flongi > 180.0) flati = flongi = 0;
         xxrec->flati = flati;
         xxrec->flongi = flongi;
      }
      
      else if (strmatchN(pp,"xmeta: ",7))                                        //  indexed metadata                   18.01
         xxrec->xmeta = zstrdup(pp+7);
   }

   if (! xxrec->pdate[0])                                                        //  supply defaults for missing items
      strcpy(xxrec->pdate,"null");

   if (! xxrec->rating[0])
      strcpy(xxrec->rating,"0");

   if (! xxrec->wwhh[0])
      strcpy(xxrec->wwhh,"null");

   if (! xxrec->fsize[0])                                                        //  18.07
      strcpy(xxrec->fsize,"null");

   if (! xxrec->tags)
      xxrec->tags = zstrdup("null");

   if (! xxrec->capt)
      xxrec->capt = zstrdup("null");

   if (! xxrec->comms)
      xxrec->comms = zstrdup("null");

   if (! xxrec->location)
      xxrec->location = zstrdup("null");

   if (! xxrec->country)
      xxrec->country = zstrdup("null");
   
   if (strmatch(xxrec->location,"null") || strmatch(xxrec->country,"null"))
      xxrec->flati = xxrec->flongi = 0;
   
   if (! xxrec->xmeta)                                                           //  18.01
      xxrec->xmeta = zstrdup("null");

   return xxrec;
}


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

//  Write the image index files sequentially, 1 record per call
//  Set ftf = 1 for first call, will be reset to 0.
//  Set xxrec = 0 to close file after last write.
//  Returns 0 if OK, otherwise +N (diagnosed).
//  Used by index_rebuild() function.

int write_xxrec_seq(xxrec_t *xxrec, int &ftf)
{
   static FILE    *fid = 0;
   char           indexfile[200];
   char           wwhh[16], fsize[16];
   int            nn, err;

   if (ftf)                                                                      //  first call
   {
      ftf = 0;
      snprintf(indexfile,200,"%s/indexC",index_dirk);                            //  create image index file
      fid = fopen(indexfile,"w");
      if (! fid) goto file_err;
   }

   if (! xxrec) {                                                                //  EOF call
      if (fid) {
         err = fclose(fid);
         fid = 0;
         if (err) goto file_err;
      }
      return 0;
   }

   nn = fprintf(fid,"file: %s\n",xxrec->file);                                   //  output: filename record
   if (! nn) goto file_err;

   if (! xxrec->pdate[0]) strcpy(xxrec->pdate,"null");                           //  missing EXIF date << "null"

   nn = fprintf(fid,"date: %s  %s\n",xxrec->pdate,xxrec->fdate);                 //  date: yyyymmddhhmmss yyyymmddhhmmss
   if (! nn) goto file_err;

   if (xxrec->rating[0])
      nn = fprintf(fid,"stars: %c\n",xxrec->rating[0]);                          //  stars: N
   else nn = fprintf(fid,"stars: 0\n");
   if (! nn) goto file_err;

   if (xxrec->wwhh[0]) strncpy0(wwhh,xxrec->wwhh,15);                            //  size: 12345x2345  12.34            18.07
   else strcpy(wwhh,"null");
   if (xxrec->fsize[0]) strncpy0(fsize,xxrec->fsize,15);
   else strcpy(fsize,"null");
   fprintf(fid,"size: %s  %s\n",wwhh,fsize);

   if (xxrec->tags)
      nn = fprintf(fid,"tags: %s\n",xxrec->tags);                                //  tags: aaaaa, bbbbb 
   else nn = fprintf(fid,"tags: null, ""\n");
   if (! nn) goto file_err;

   if (xxrec->capt)
      nn = fprintf(fid,"capt: %s\n",xxrec->capt);                                //  caption: text
   else nn = fprintf(fid,"capt: null\n");
   if (! nn) goto file_err;

   if (xxrec->comms)
      nn = fprintf(fid,"comms: %s\n",xxrec->comms);                              //  comments: text
   else nn = fprintf(fid,"comms: null\n");
   if (! nn) goto file_err;

   nn = fprintf(fid,"gtags: %s^ %s^ %.4f^ %.4f\n",
         xxrec->location, xxrec->country, xxrec->flati, xxrec->flongi);
   if (! nn) goto file_err;

   if (xxrec->xmeta)
      nn = fprintf(fid,"xmeta: %s\n",xxrec->xmeta);                              //  xmeta: name1^ name2^ ...           18.01
   else nn = fprintf(fid,"xmeta: null\n");
   if (! nn) goto file_err;

   nn = fprintf(fid,"END\n");                                                    //  EOL                                18.01
   if (! nn) goto file_err;

   return 0;

file_err:
   zmessageACK(Mwin,"image index write error\n %s",strerror(errno));
   if (fid) fclose(fid);
   fid = 0;
   return 2;
}