summaryrefslogtreecommitdiff
path: root/tex/context/base/mkiv/publ-ini.lua
blob: aa55b40e99596c953820dccf4ca170a4c1551393 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
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
if not modules then modules = { } end modules ['publ-ini'] = {
    version   = 1.001,
    comment   = "this module part of publication support",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- bah .. this 200 locals limit again ... so we need to split it as adding more
-- do ... ends makes it messier

-- plug the list sorted in the list mechanism (specification.sortorder)

-- If we define two datasets with the same bib file we can consider
-- sharing the data but that means that we need to have a parent which
-- in turn makes things messy if we start manipulating entries in
-- different ways (future) .. not worth the trouble as we will seldom
-- load big bib files many times and even then ... fonts are larger.

-- A potential optimization is to work with current_dataset, current_tag when
-- fetching fields but the code become real messy that way (many currents). The
-- gain is not that large anyway because not much publication stuff is flushed.

local next, rawget, type, tostring, tonumber = next, rawget, type, tostring, tonumber
local match, find, gsub = string.match, string.find, string.gsub
local concat, sort, tohash = table.concat, table.sort, table.tohash
local mod = math.mod
local formatters = string.formatters
local allocate = utilities.storage.allocate
local settings_to_array, settings_to_set = utilities.parsers.settings_to_array, utilities.parsers.settings_to_set
local sortedkeys, sortedhash = table.sortedkeys, table.sortedhash
local setmetatableindex = table.setmetatableindex
local lpegmatch = lpeg.match
local P, S, C, Ct, Cs, R, Carg = lpeg.P, lpeg.S, lpeg.C, lpeg.Ct, lpeg.Cs, lpeg.R, lpeg.Carg
local upper = characters.upper

local report             = logs.reporter("publications")
local report_cite        = logs.reporter("publications","cite")
local report_list        = logs.reporter("publications","list")
local report_suffix      = logs.reporter("publications","suffix")

local trace              = false  trackers.register("publications",                 function(v) trace            = v end)
local trace_cite         = false  trackers.register("publications.cite",            function(v) trace_cite       = v end)
local trace_missing      = false  trackers.register("publications.cite.missing",    function(v) trace_missing    = v end)
local trace_references   = false  trackers.register("publications.cite.references", function(v) trace_references = v end)
local trace_detail       = false  trackers.register("publications.detail",          function(v) trace_detail     = v end)
local trace_suffixes     = false  trackers.register("publications.suffixes",        function(v) trace_suffixes   = v end)

publications             = publications or { }
local datasets           = publications.datasets
local writers            = publications.writers
local casters            = publications.casters
local detailed           = publications.detailed
local enhancer           = publications.enhancer
local enhancers          = publications.enhancers

local tracers            = publications.tracers or { }
publications.tracers     = tracers

local setmacro           = interfaces.setmacro   -- todo
local setcounter         = tex.setcounter        -- todo
local variables          = interfaces.variables

local v_local            = variables["local"]
local v_global           = variables["global"]

local v_force            = variables.force
local v_normal           = variables.normal
local v_reverse          = variables.reverse
local v_none             = variables.none
local v_yes              = variables.yes
local v_no               = variables.no
local v_all              = variables.all
local v_always           = variables.always
local v_text             = variables.text
local v_doublesided      = variables.doublesided
local v_default          = variables.default
local v_dataset          = variables.dataset

local conditionals       = tex.conditionals

local isdefined          = tex.isdefined

----- basicsorter        = sorters.basicsorter -- (a,b)
----- sortstripper       = sorters.strip
----- sortsplitter       = sorters.splitters.utf

local manipulators       = typesetters.manipulators
local splitmanipulation  = manipulators.splitspecification
local applymanipulation  = manipulators.applyspecification
local manipulatormethods = manipulators.methods

-- this might move elsewhere

manipulatormethods.Word  = converters.Word
manipulatormethods.WORD  = converters.WORD
manipulatormethods.Words = converters.Words
manipulatormethods.WORDS = converters.WORDS

local context                     = context
local commands                    = commands
local implement                   = interfaces.implement

local ctx_doifelse                = commands.doifelse
local ctx_doif                    = commands.doif
local ctx_doifnot                 = commands.doifnot
local ctx_gobbletwoarguments      = context.gobbletwoarguments

local ctx_btxhandlelistentry      = context.btxhandlelistentry
local ctx_btxhandlecombientry     = context.btxhandlecombientry
local ctx_btxchecklistentry       = context.btxchecklistentry

local ctx_btxsetdataset           = context.btxsetdataset
local ctx_btxsettag               = context.btxsettag
local ctx_btxsetnumber            = context.btxsetnumber
local ctx_btxsetlanguage          = context.btxsetlanguage
local ctx_btxsetcombis            = context.btxsetcombis
local ctx_btxsetcategory          = context.btxsetcategory
local ctx_btxsetfirst             = context.btxsetfirst
local ctx_btxsetsecond            = context.btxsetsecond
local ctx_btxsetsuffix            = context.btxsetsuffix
local ctx_btxsetinternal          = context.btxsetinternal
local ctx_btxsetlefttext          = context.btxsetlefttext
local ctx_btxsetrighttext         = context.btxsetrighttext
local ctx_btxsetbefore            = context.btxsetbefore
local ctx_btxsetafter             = context.btxsetafter
local ctx_btxsetbacklink          = context.btxsetbacklink
local ctx_btxsetfirstinternal     = context.btxsetfirstinternal
local ctx_btxsetlastinternal      = context.btxsetlastinternal
local ctx_btxsetauthorfield       = context.btxsetauthorfield

-- local ctx_btxsetdataset           = function(s) setmacro("currentbtxdataset",       s) end -- context.btxsetdataset
-- local ctx_btxsettag               = function(s) setmacro("currentbtxtag",           s) end -- context.btxsettag
-- local ctx_btxsetnumber            = function(s) setmacro("currentbtxnumber",        s) end -- context.btxsetnumber
-- local ctx_btxsetlanguage          = function(s) setmacro("currentbtxlanguage",      s) end -- context.btxsetlanguage
-- local ctx_btxsetcombis            = function(s) setmacro("currentbtxcombis",        s) end -- context.btxsetcombis
-- local ctx_btxsetcategory          = function(s) setmacro("currentbtxcategory",      s) end -- context.btxsetcategory
-- local ctx_btxsetfirst             = function(s) setmacro("currentbtxfirst",         s) end -- context.btxsetfirst
-- local ctx_btxsetsecond            = function(s) setmacro("currentbtxsecond",        s) end -- context.btxsetsecond
-- local ctx_btxsetsuffix            = function(s) setmacro("currentbtxsuffix",        s) end -- context.btxsetsuffix
-- local ctx_btxsetinternal          = function(s) setmacro("currentbtxinternal",      s) end -- context.btxsetinternal
-- local ctx_btxsetlefttext          = function(s) setmacro("currentbtxlefttext",      s) end -- context.btxsetlefttext
-- local ctx_btxsetrighttext         = function(s) setmacro("currentbtxrighttext",     s) end -- context.btxsetrighttext
-- local ctx_btxsetbefore            = function(s) setmacro("currentbtxbefore",        s) end -- context.btxsetbefore
-- local ctx_btxsetafter             = function(s) setmacro("currentbtxafter",         s) end -- context.btxsetafter
-- local ctx_btxsetbacklink          = function(s) setmacro("currentbtxbacklink",      s) end -- context.btxsetbacklink
-- local ctx_btxsetfirstinternal     = function(s) setmacro("currentbtxfirstinternal", s) end -- context.btxsetfirstinternal
-- local ctx_btxsetlastinternal      = function(s) setmacro("currentbtxlastinternal",  s) end -- context.btxsetlastinternal

local ctx_btxsetfirstpage         = context.btxsetfirstpage
local ctx_btxsetlastpage          = context.btxsetlastpage

local ctx_btxstartcite            = context.btxstartcite
local ctx_btxstopcite             = context.btxstopcite
local ctx_btxstartciteauthor      = context.btxstartciteauthor
local ctx_btxstopciteauthor       = context.btxstopciteauthor
local ctx_btxstartsubcite         = context.btxstartsubcite
local ctx_btxstopsubcite          = context.btxstopsubcite
local ctx_btxstartlistentry       = context.btxstartlistentry
local ctx_btxstoplistentry        = context.btxstoplistentry
local ctx_btxstartcombientry      = context.btxstartcombientry
local ctx_btxstopcombientry       = context.btxstopcombientry

local ctx_btxflushauthor          = context.btxflushauthor

local ctx_btxsetnoflistentries    = context.btxsetnoflistentries
local ctx_btxsetcurrentlistentry  = context.btxsetcurrentlistentry
local ctx_btxsetcurrentlistindex  = context.btxsetcurrentlistindex

local ctx_btxsetcount             = context.btxsetcount
local ctx_btxsetconcat            = context.btxsetconcat

local ctx_btxcitesetup            = context.btxcitesetup
local ctx_btxsubcitesetup         = context.btxsubcitesetup
local ctx_btxnumberingsetup       = context.btxnumberingsetup
local ctx_btxpagesetup            = context.btxpagesetup
local ctx_btxlistsetup            = context.btxlistsetup

local trialtypesetting            = context.trialtypesetting

languages.data                    = languages.data       or { }
local data                        = languages.data

local specifications              = publications.specifications
local currentspecification        = specifications[false]
local ignoredfields               = { }
publications.currentspecification = currentspecification

local function setspecification(name)
    currentspecification = specifications[name]
    if trace then
        report("setting specification %a",type(name) == "string" and name or "anything")
    end
    publications.currentspecification = currentspecification
end

publications.setspecification = setspecification

implement {
    name      = "btxsetspecification",
    actions   = setspecification,
    arguments = "string",
}

local optionalspace  = lpeg.patterns.whitespace^0
local prefixsplitter = optionalspace * lpeg.splitat(optionalspace * P("::") * optionalspace)

statistics.register("publications load time", function()
    local publicationsstats = publications.statistics
    local nofbytes = publicationsstats.nofbytes
    if nofbytes > 0 then
        return string.format("%s seconds, %s bytes, %s definitions, %s shortcuts",
            statistics.elapsedtime(publications),
            nofbytes,
            publicationsstats.nofdefinitions or 0,
            publicationsstats.nofshortcuts or 0
        )
    else
        return nil
    end
end)

logs.registerfinalactions(function()
    local done    = false
    local unknown = false
    for name, dataset in sortedhash(datasets) do
        for command, n in sortedhash(dataset.commands) do
            if not done then
                logs.startfilelogging(report,"used btx commands")
                done = true
            end
            if isdefined(command) then
                report("%-20s %-20s % 5i %s",name,command,n,"known")
            elseif isdefined(upper(command)) then
                report("%-20s %-20s % 5i %s",name,command,n,"KNOWN")
            else
                report("%-20s %-20s % 5i %s",name,command,n,"unknown")
                unknown = true
            end
        end
    end
    if done then
        logs.stopfilelogging()
    end
    if unknown and logs.loggingerrors() then
        logs.starterrorlogging(report,"unknown btx commands")
        for name, dataset in sortedhash(datasets) do
            for command, n in sortedhash(dataset.commands) do
                if not isdefined(command) and not isdefined(upper(command)) then
                    report("%-20s %-20s % 5i %s",name,command,n,"unknown")
                end
            end
        end
        logs.stoperrorlogging()
    end
end)

-- multipass, we need to sort because hashing is random per run and not per
-- version (not the best changed feature of lua)

local collected = allocate()
local tobesaved = allocate()

do

    local function serialize(t)
        local f_key_table  = formatters[" [%q] = {"]
        local f_key_string = formatters["  %s = %q,"]
        local r = { "return {" }
        local m = 1
        for tag, entry in sortedhash(t) do
            m = m + 1
            r[m] = f_key_table(tag)
            local s = sortedkeys(entry)
            for i=1,#s do
                local k = s[i]
                m = m + 1
                r[m] = f_key_string(k,entry[k])
            end
            m = m + 1
            r[m] = " },"
        end
        r[m] = "}"
        return concat(r,"\n")
    end

    local function finalizer()
        local prefix = tex.jobname -- or environment.jobname
        local setnames = sortedkeys(datasets)
        for i=1,#setnames do
            local name     = setnames[i]
            local dataset  = datasets[name]
            local userdata = dataset.userdata
            local checksum = nil
            local username = file.addsuffix(file.robustname(formatters["%s-btx-%s"](prefix,name)),"lua")
            if userdata and next(userdata) then
                if job.passes.first then
                    local newdata = serialize(userdata)
                    checksum = md5.HEX(newdata)
                    io.savedata(username,newdata)
                end
            else
                os.remove(username)
                username = nil
            end
            local loaded  = dataset.loaded
            local sources = dataset.sources
            local used    = { }
            for i=1,#sources do
                local source = sources[i]
             -- if loaded[source.filename] ~= "previous" then -- needs checking
                if loaded[source.filename] ~= "previous" or loaded[source.filename] == "current" then
                    used[#used+1] = source
                end
            end
            tobesaved[name] = {
                usersource = {
                    filename = username,
                    checksum = checksum,
                },
                datasources = used,
            }
        end
    end

    local function initializer()
        statistics.starttiming(publications)
        for name, state in sortedhash(collected) do
            local dataset     = datasets[name]
            local datasources = state.datasources
            local usersource  = state.usersource
            if datasources then
                for i=1,#datasources do
                    local filename = datasources[i].filename
                    publications.load {
                        dataset  = dataset,
                        filename = filename,
                        kind     = "previous"
                    }
                end
            end
            if usersource then
                dataset.userdata = table.load(usersource.filename) or { }
            end
        end
        statistics.stoptiming(publications)
        function initializer() end -- will go, for now, runtime loaded
    end

    job.register('publications.collected',tobesaved,initializer,finalizer)

end

-- we want to minimize references as there can be many (at least
-- when testing)

local nofcitations = 0
local usedentries  = nil
local citetolist   = nil
local listtocite   = nil
local listtolist   = nil

do

    local initialize = nil -- we delay

    initialize = function(t)
        usedentries     = allocate { }
        citetolist      = allocate { }
        listtocite      = allocate { }
        listtolist      = allocate { }
        local names     = { }
        local p_collect = (C(R("09")^1) * Carg(1) / function(s,entry) listtocite[tonumber(s)] = entry end + P(1))^0
        local nofunique = 0
        local nofreused = 0
     -- local internals = references.sortedinternals -- todo: when we need it more than once
     -- for i=1,#internals do                        -- but currently we don't do this when not
     --     local entry = internals[i]               -- needed anyway so ...
        local internals = structures.references.internals
        for i, entry in sortedhash(internals) do
            local metadata = entry.metadata
            if metadata then
                local kind = metadata.kind
                if kind == "full" then
                    -- reference (in list)
                    local userdata = entry.userdata
                    if userdata then
                        local tag = userdata.btxref
                        if tag then
                            local set = userdata.btxset or v_default
                            local s = usedentries[set]
                            if s then
                                local u = s[tag]
                                if u then
                                    u[#u+1] = entry
                                else
                                    s[tag] = { entry }
                                end
                                nofreused = nofreused + 1
                            else
                                usedentries[set] = { [tag] = { entry } }
                                nofunique = nofunique + 1
                            end
                            -- alternative: collect prev in group
                            local int = tonumber(userdata.btxint)
                            if int then
                                listtocite[int] = entry
                            end
                            local detail = datasets[set].details[tag]
                            -- todo: these have to be pluggable
                            if detail then
                                local author = detail.author
                                if author then
                                    for i=1,#author do
                                        local a = author[i]
                                        local s = a.surnames
                                        if s then
                                            local c = concat(s,"+")
                                            local n = names[c]
                                            if n then
                                                n[#n+1] = a
                                                break
                                            else
                                                names[c] = { a }
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                elseif kind == "btx" then
                    -- list entry (each cite)
                    local userdata = entry.userdata
                    if userdata then
                        local int = tonumber(userdata.btxint)
                        if int then
                            citetolist[int] = entry
                        end
                    end
                end
            end
        end
        for k, v in sortedhash(names) do
            local n = #v
            if n > 1 then
                local original = v[1].original
                for i=2,n do
                    if original ~= v[i].original then
                        report("potential clash in name %a",k)
                        for i=1,n do
                            v[i].state = 1
                        end
                        break
                    end
                end
            end
        end
        if trace_detail then
            report("%s unique references, %s reused entries",nofunique,nofreused)
        end
        initialize = nil
    end

    usedentries = setmetatableindex(function(_,k) if initialize then initialize() end return usedentries[k] end)
    citetolist  = setmetatableindex(function(_,k) if initialize then initialize() end return citetolist [k] end)
    listtocite  = setmetatableindex(function(_,k) if initialize then initialize() end return listtocite [k] end)
    listtolist  = setmetatableindex(function(_,k) if initialize then initialize() end return listtolist [k] end)

    function publications.usedentries()
        if initialize then
            initialize()
        end
        return usedentries
    end

end

-- match:
--
-- [current|previous|following] section
-- [current|previous|following] block
-- [current|previous|following] component
--
-- by prefix
-- by dataset

local findallused do

    local reported = { }
    ----- finder   = publications.finder

    findallused = function(dataset,reference,internal,forcethem)
        local current  = datasets[dataset]
        local finder   = publications.finder -- for the moment, not yet in all betas
        local find     = finder and finder(current,reference)
        local tags     = not find and settings_to_array(reference)
        local todo     = { }
        local okay     = { } -- only if mark
        local allused  = usedentries[dataset] or { }
     -- local allused  = usedentries[dataset] -- only test
        local luadata  = current.luadata
        local details  = current.details
        local ordered  = current.ordered
        if allused then -- always true
            local registered = { }
            local function register(tag)
                local entry = forcethem and luadata[tag]
                if entry then
                    if registered[tag] then
                        if trace_cite then
                            report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"already cited (1)")
                        end
                        return
                    elseif trace_cite then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"okay")
                    end
                    okay[#okay+1] = entry
                 -- todo[tag] = true
                    registered[tag] = true
                    return tag
                end
                entry = allused[tag]
                if trace_cite then
                    report_cite("dataset: %s, tag: %s, used: % t",dataset,tag,table.sortedkeys(allused))
                end
                if not entry then
                    local parent = details[tag].parent
                    if parent then
                        entry = allused[parent]
                    end
                    if entry then
                        report("using reference of parent %a for %a",parent,tag)
                        tag = parent
                    elseif trace_cite then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"not used")
                    end
                elseif trace_cite then
                    report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"used")
                end
                if registered[tag] then
                    if trace_cite then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"already cited (2)")
                    end
                    return
                end
                if entry then
                    -- only once in a list but at some point we can have more (if we
                    -- decide to duplicate)
                    if #entry == 1 then
                        entry = entry[1]
                    else
                        -- same block and section
                        local done = false
                        if internal and internal > 0 then
                            -- first following in list
                            for i=1,#entry do
                                local e = entry[i]
                                if e.references.internal > internal then
                                    done = e
                                    break
                                end
                            end
                            if not done then
                                -- last preceding in list
                                for i=1,#entry do
                                    local e = entry[i]
                                    if e.references.internal < internal then
                                        done = e
                                    else
                                        break
                                    end
                                end
                            end
                        end
                        if done then
                            entry = done
                        else
                            entry = entry[1]
                        end
                    end
                    if not entry then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"no entry (1)")
                    elseif trace_cite then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"new entry")
                    end
                    okay[#okay+1] = entry
                elseif not entry then
                    if trace_cite then
                        report_cite("dataset: %s, tag: %s, state: %s",dataset,tag,"no entry (2)")
                    end
        -- okay[#okay+1] = luadata[tag]
                end
                todo[tag] = true
                registered[tag] = true
                return tag
            end
            if reference == "*" then
                tags = { }
                for i=1,#ordered do
                    local tag = ordered[i].tag
                    tag = register(tag)
                    tags[#tags+1] = tag
                end
            elseif find then
                tags = { }
                for i=1,#ordered do
                    local entry = ordered[i]
                    if find(entry) then
                        local tag = entry.tag
                        tag = register(tag)
                        tags[#tags+1] = tag
                    end
                end
                if #tags == 0 and not reported[reference] then
                    tags[1] = reference
                    reported[reference] = true
                end
            else
                for i=1,#tags do
                    local tag = tags[i]
                    if luadata[tag] then
                        tag = register(tag)
                        tags[i] = tag
                    elseif not reported[tag] then
                        reported[tag] = true
                        report_cite("non-existent entry %a in %a",tag,dataset)
                    end
                end
            end
        elseif find then
            tags = { }
            for i=1,#ordered do
                local entry = ordered[i]
                if find(entry) then
                    local tag    = entry.tag
                    local parent = details[tag].parent
                    if parent then
                        tag = parent
                    end
                    tags[#tags+1] = tag
                    todo[tag] = true
                 -- okay[#okay+1] = entry -- only test
                end
            end
            if #tags == 0 and not reported[reference] then
                tags[1] = reference
                reported[reference] = true
            end
        else
            for i=1,#tags do
                local tag    = tags[i]
                local parent = details[tag].parent
                if parent then
                    tag = parent
                    tags[i] = tag
                end
                local entry = luadata[tag]
                if entry then
                    todo[tag] = true
                 -- okay[#okay+1] = entry -- only test
                elseif not reported[tag] then
                    reported[tag] = true
                    report_cite("non-existent entry %a in %a",tag,dataset)
                end
            end
        end
        return okay, todo, tags
    end

    local firstoftwoarguments  = context.firstoftwoarguments
    local secondoftwoarguments = context.secondoftwoarguments

    implement {
        name      = "btxdoifelsematches",
        arguments = "3 strings",
        actions   = function(dataset,tag,expression)
            local find = publications.finder(dataset,expression)
            local okay = false
            if find then
                local d = datasets[dataset]
                if d then
                    local e = d.luadata[tag]
                    if e and find(e) then
                        firstoftwoarguments()
                        return
                    end
                end
            end
            secondoftwoarguments()
        end
    }

end

local function unknowncite(reference)
    ctx_btxsettag(reference)
    if trace_detail then
        report("expanding %a cite setup %a","unknown","unknown")
    end
    ctx_btxcitesetup("unknown")
end

local concatstate = publications.concatstate

-- hidden : mark for list, don't show in text
-- list   : mark for list, show in text only when in list
-- text   : not to list, show in text
-- always : mark for list, show in text

local marked_todo    = false -- keeps track or not yet flushed
local marked_dataset = false
local marked_list    = false -- the sequential list (we flush in order, not by unordered hash)
local marked_method  = false

local function marknocite(dataset,tag,nofcitations,setup)
    ctx_btxstartcite()
    ctx_btxsetdataset(dataset)
    ctx_btxsettag(tag)
    ctx_btxsetbacklink(nofcitations)
    if trace_detail then
        report("expanding cite setup %a",setup)
    end
    ctx_btxcitesetup(setup)
    ctx_btxstopcite()
end

local function markcite(dataset,tag,flush)
    if not marked_todo then
        return 0
    end
    local citation = marked_todo[tag]
    if not citation then
        return 0
    end
    if citation == true then
        nofcitations = nofcitations + 1
        if trace_cite then
            report_cite("mark, dataset: %s, tag: %s, number: %s, state: %s",dataset,tag,nofcitations,"cited")
        end
        if flush then
            marknocite(dataset,tag,nofcitations,"nocite")
        end
        marked_todo[tag] = nofcitations -- signal that it's marked
        return nofcitations
    else
        return citation
    end
end

local function btxflushmarked()
    if marked_list and marked_todo then
        for i=1,#marked_list do
            -- keep order
            local tag = marked_list[i]
            local tbm = marked_todo[tag]
            if tbm == true or not tbm then
                nofcitations = nofcitations + 1
                local setup = (tbm or marked_method == v_always) and "nocite" or "invalid"
                marknocite(marked_dataset,tag,nofcitations,setup)
                if trace_cite then
                    report_cite("mark, dataset: %s, tag: %s, number: %s, setup: %s",marked_dataset,tag,nofcitations,setup)
                end
            else
                -- a number signaling being marked
            end
        end
    end
    marked_todo    = false
    marked_dataset = false
    marked_list    = false
    marked_method  = false
end

implement { name = "btxflushmarked", actions = btxflushmarked }

-- basic access

local function getfield(dataset,tag,name) -- for the moment quick and dirty
    local d = datasets[dataset].luadata[tag]
    return d and d[name]
end

local function getdetail(dataset,tag,name) -- for the moment quick and dirty
    local d = datasets[dataset].details[tag]
    return d and d[name]
end

local function getcasted(dataset,tag,field,specification)
    local current = datasets[dataset]
    if current then
        local data = current.luadata[tag]
        if data then
            local category = data.category
            if not specification then
                specification = currentspecification
            end
            local catspec = specification.categories[category]
            if not catspec then
                return false
            end
            local fields = catspec.fields
            if fields then
                local sets = catspec.sets
                if sets then
                    local set = sets[field]
                    if set then
                        for i=1,#set do
                            local field = set[i]
                            local value = fields[field] and data[field] -- redundant check
                            if value then
                                local kind = specification.types[field]
                                return detailed[kind][value], field, kind
                            end
                        end
                    end
                end
                local value = fields[field] and data[field] -- redundant check
                if value then
                    local kind = specification.types[field]
                    return detailed[kind][value], field, kind
                end
            end
            local data = current.details[tag]
            if data then
                local kind = specification.types[field]
                return data[field], field, kind -- no check
            end
        end
    end
end

local function getfaster(current,data,details,field,categories,types)
    local category = data.category
    local catspec  = categories[category]
    if not catspec then
        return false
    end
    local fields = catspec.fields
    if fields then
        local sets = catspec.sets
        if sets then
            local set = sets[field]
            if set then
                for i=1,#set do
                    local field = set[i]
                    local value = fields[field] and data[field] -- redundant check
                    if value then
                        local kind = types[field]
                        return detailed[kind][value], field, kind
                    end
                end
            end
        end
        local value = fields[field] and data[field] -- redundant check
        if value then
            local kind = types[field]
            return detailed[kind][value]
        end
    end
    if details then
        local kind = types[field]
        return details[field]
    end
end

local function getdirect(dataset,data,field,catspec) -- no field check, no dataset check
    local catspec = (catspec or currentspecification).categories[data.category]
    if not catspec then
        return false
    end
    local fields = catspec.fields
    if fields then
        local sets = catspec.sets
        if sets then
            local set = sets[field]
            if set then
                for i=1,#set do
                    local field = set[i]
                    local value = fields[field] and data[field] -- redundant check
                    if value then
                        return value
                    end
                end
            end
        end
        return fields[field] and data[field] or nil -- redundant check
    end
end

local function getfuzzy(data,field,categories) -- no field check, no dataset check
    local catspec
    if categories then
        local category = data.category
        if category then
            catspec = categories[data.category]
        end
    end
    if not field then
        return
    elseif not catspec then
        return data[field]
    end
    local fields = catspec.fields
    if fields then
        local sets = catspec.sets
        if sets then
            local set = sets[field]
            if set then
                for i=1,#set do
                    local field = set[i]
                    local value = fields[field] and data[field] -- redundant check
                    if value then
                        return value
                    end
                end
            end
        end
        return fields[field] and data[field] or nil -- redundant check
    end
end

publications.getfield  = getfield
publications.getdetail = getdetail
publications.getcasted = getcasted
publications.getfaster = getfaster
publications.getdirect = getdirect
publications.getfuzzy  = getfuzzy

-- this needs to be checked: a specific type should have a checker

-- author pagenumber keyword url

-- function commands.btxsingularorplural(dataset,tag,name)
--     local d = getcasted(dataset,tag,name)
--     if type(d) == "table" then
--         d = #d <= 1
--     else
--         d = true
--     end
--     ctx_doifelse(d)
-- end

-- function commands.oneorrange(dataset,tag,name)
--     local d = datasets[dataset].luadata[tag] -- details ?
--     if d then
--         d = d[name]
--     end
--     if type(d) == "string" then
--         d = find(d,"%-")
--     else
--         d = false
--     end
--     ctx_doifelse(not d) -- so singular is default
-- end

-- function commands.firstofrange(dataset,tag,name)
--     local d = datasets[dataset].luadata[tag] -- details ?
--     if d then
--         d = d[name]
--     end
--     if type(d) == "string" then
--         context(match(d,"([^%-]+)"))
--     end
-- end

local inspectors   = allocate()
local nofmultiple  = allocate()
local firstandlast = allocate()

publications.inspectors = inspectors
inspectors.nofmultiple  = nofmultiple
inspectors.firstandlast = firstandlast

function nofmultiple.author(d)
    return type(d) == "table" and #d or 0
end

function publications.singularorplural(dataset,tag,name)
    local data, field, kind = getcasted(dataset,tag,name)
    if data then
        local test = nofmultiple[kind]
        if test then
            local n = test(data)
            return not n or n < 2
        end
    end
    return true
end

function firstandlast.range(d)
    if type(d) == "table" then
        return d[1], d[2]
    end
end

firstandlast.pagenumber = firstandlast.range

function publications.oneorrange(dataset,tag,name)
    local data, field, kind = getcasted(dataset,tag,name)
    if data then
        local test = firstandlast[kind]
        if test then
            local first, last = test(data)
            return not (first and last)
        end
    end
    return nil -- nothing at all
end

function publications.firstofrange(dataset,tag,name)
    local data, field, kind = getcasted(dataset,tag,name)
    if data then
        local test = firstandlast[kind]
        if test then
            local first = test(data)
            if first then
                return first
            end
        end
    end
end

function publications.lastofrange(dataset,tag,name)
    local data, field, kind = getcasted(dataset,tag,name)
    if data then
        local test = firstandlast[kind]
        if test then
            local first, last = test(data)
            if last then
                return last
            end
        end
    end
end

implement {
    name      = "btxsingularorplural",
    actions   = { publications.singularorplural, ctx_doifelse },
    arguments = "3 strings"
}

implement {
    name      = "btxoneorrange",
    actions   = { publications.oneorrange, function(b) if b == nil then ctx_gobbletwoarguments() else ctx_doifelse(b) end end },
    arguments = "3 strings"
}

implement {
    name      = "btxfirstofrange",
    actions   = { publications.firstofrange, context },
    arguments = "3 strings"
}

implement {
    name      = "btxlastofrange",
    actions   = { publications.lastofrange, context },
    arguments = "3 strings"
}

-- basic loading

function publications.usedataset(specification)
    specification.kind = "current"
    publications.load(specification)
end

implement {
    name      = "btxusedataset",
    actions   = publications.usedataset,
    arguments = {
        {
            { "specification" },
            { "dataset" },
            { "filename" },
        }
    }
}

implement {
    name       = "convertbtxdatasettoxml",
    arguments  = { "string", true },
    actions    = publications.converttoxml
}

-- enhancing

do

    -- maybe not redo when already done

    local function shortsorter(a,b)
        local ay = a[2] -- year
        local by = b[2] -- year
        if ay ~= by then
            return ay < by
        end
        local ay = a[3] -- suffix
        local by = b[3] -- suffix
        if ay ~= by then
            -- bah, bah, bah
            local an = tonumber(ay)
            local bn = tonumber(by)
            if an and bn then
                return an < bn
            else
                return ay < by
            end
        end
        return a[4] < b[4]
    end

    -- We could avoid loops by combining enhancers but that makes it only
    -- more messy and for documents that use publications the few extra milli
    -- seconds are irrelevant (there is for sure more to gain by proper coding
    -- of the source and or style).

    local f_short = formatters["%s%02i"]

    function publications.enhancers.suffixes(dataset)
        if not dataset then
            return -- bad news
        else
            report("analyzing previous publication run for %a",dataset.name)
        end
        dataset.suffixed = true
        --
        local used = usedentries[dataset.name]
        if not used then
            return -- probably a first run
        end
        local luadata  = dataset.luadata
        local details  = dataset.details
        local ordered  = dataset.ordered
        if not luadata or not details or not ordered then
            report("nothing to be analyzed in %a",dataset.name)
            return -- also bad news
        end
        -- we have two suffixes: author (dependent of type) and short
        local kind    = dataset.authorconversion or "name"
        local fields  = { "author", "editor" } -- will be entry in data definition
        local shorts  = { }
        local authors = { }
        local hasher  = publications.authorhashers[kind]
        local shorter = publications.authorhashers.short
        for i=1,#ordered do
            local entry = ordered[i]
            if entry then
                local tag = entry.tag
                if tag then
                    local use = used[tag]
                    if use then
                        -- use is a table of used list entries (so there can be more) and we just look at
                        -- the first one for btx properties
                        local listentry = use[1]
                        local userdata  = listentry.userdata
                        local btxspc    = userdata and userdata.btxspc
                        if btxspc then
                            -- we could act on the 3rd arg returned by getcasted but in general any string will do
                            -- so we deal with it in the author hashers ... maybe some day ...
                            local done = false
                            for i=1,#fields do
                                local field = fields[i]
                                local author = getcasted(dataset,tag,field,specifications[btxspc])
                                local kind   = type(author)
                                if kind == "table" or kind == "string" then
                                    if u then
                                        u = listentry.entries.text -- hm
                                    else
                                        u = "0"
                                    end
                                    local year  = tonumber(entry.year) or 9999
                                    local data  = { tag, year, u, i }
                                    -- authors
                                    local hash  = hasher(author)
                                    local found = authors[hash]
                                    if not found then
                                        authors[hash] = { data }
                                    else
                                        found[#found+1] = data
                                    end
                                    -- shorts
                                    local hash  = shorter(author)
                                    local short = f_short(hash,mod(year,100))
                                    local found = shorts[short]
                                    if not found then
                                        shorts[short] = { data }
                                    else
                                        found[#found+1] = data
                                    end
                                    done = true
                                    break
                                end
                            end
                            if not done then
                                report("unable to create short for %a, needs one of [%,t]",tag,fields)
                            end
                        else
                            --- no spec so let's forget about it
                        end
                    end
                end
            end
        end
        local function addsuffix(hashed,key,suffixkey)
            for hash, tags in sortedhash(hashed) do -- ordered ?
                local n = #tags
                if n == 0 then
                    -- skip
                elseif n == 1 then
                    local tagdata = tags[1]
                    local tag     = tagdata[1]
                    local detail  = details[tag]
                    local entry   = luadata[tag]
                    local year    = entry.year
                    detail[key]   = hash
                elseif n > 1 then
                    sort(tags,shortsorter) -- or take first -- todo: proper utf sorter
                    local lastyear = nil
                    local suffix   = nil
                    local previous = nil
                    for i=1,n do
                        local tagdata = tags[i]
                        local tag     = tagdata[1]
                        local detail  = details[tag]
                        local entry   = luadata[tag]
                        local year    = entry.year
                        detail[key]   = hash
                        if not year or year ~= lastyear then
                            lastyear = year
                            suffix = 1
                        else
                            if previous and suffix == 1 then
                                previous[suffixkey] = suffix
                            end
                            suffix = suffix + 1
                            detail[suffixkey] = suffix
                        end
                        previous = detail
                    end
                end
                if trace_suffixes then
                    for i=1,n do
                        local tag    = tags[i][1]
                        local year   = luadata[tag].year
                        local suffix = details[tag].suffix
                        if suffix then
                            report_suffix("%s: tag %a, hash %a, year %a, suffix %a",key,tag,hash,year or '',suffix or '')
                        else
                            report_suffix("%s: tag %a, hash %a, year %a",key,tag,hash,year or '')
                        end
                    end
                end
            end
        end
        addsuffix(shorts, "shorthash", "shortsuffix") -- todo: shorthash
        addsuffix(authors,"authorhash","authorsuffix")
    end

 -- utilities.sequencers.appendaction(enhancer,"system","publications.enhancers.suffixes")

end

implement {
    name      = "btxaddentry",
    arguments = "3 strings",
    actions   = function(name,settings,content)
        local dataset = datasets[name]
        if dataset then
            publications.addtexentry(dataset,settings,content)
        end
    end,
}

function publications.checkeddataset(name,default)
    local dataset = rawget(datasets,name)
    if dataset then
        return name
    elseif default and default ~= "" then
        return default
    else
        report("unknown dataset %a, forcing %a",name,v_default)
        return v_default
    end
end

implement {
    name      = "btxsetdataset",
    arguments = "2 strings",
    actions   = { publications.checkeddataset, context },
}

implement {
    name      = "btxsetentry",
    arguments = "2 strings",
    actions   = function(name,tag)
        local dataset = rawget(datasets,name)
        if dataset then
            if dataset.luadata[tag] then
                context(tag)
            else
                report("unknown tag %a in dataset %a",tag,name)
            end
        else
            report("unknown dataset %a",name)
        end
    end,
}

-- rendering of fields

do

    local typesetters        = { }
    publications.typesetters = typesetters

    local function defaulttypesetter(field,value,manipulator)
        if value and value ~= "" then
            value = tostring(value)
            context(manipulator and applymanipulation(manipulator,value) or value)
        end
    end

    setmetatableindex(typesetters,function(t,k)
        local v = defaulttypesetter
        t[k] = v
        return v
    end)

    function typesetters.string(field,value,manipulator)
        if value and value ~= "" then
            context(manipulator and applymanipulation(manipulator,value) or value)
        end
    end

    function typesetters.author(field,value,manipulator)
        ctx_btxflushauthor(field)
    end

 -- function typesetters.url(field,value,manipulator)
 --     ....
 -- end

    -- if there is no specification then we're in trouble but there is
    -- always a default anyway
    --
    -- there's also always a fields table but it can be empty due to
    -- lack of specifications
    --
    -- then there can be cases where we have no specification for instance
    -- when we have a special kind of database

    local splitter = lpeg.splitat(":")

    local function permitted(category,field)
        local catspec = currentspecification.categories[category]
        if not catspec then
            report("invalid category %a, %s",category,"no specification") -- can't happen
            return false
        end
        local fields = catspec.fields
        if not fields then
            report("invalid category %a, %s",category,"no fields") -- can't happen
            return false
        end
        if ignoredfields and ignoredfields[field] then
            return false
        end
        local virtualfields = currentspecification.virtualfields
        if virtualfields and virtualfields[field] then
            return true
        end
        local sets = catspec.sets
        if sets then
            local set = sets[field]
            if set then
                return set
            end
        end
        if fields[field] then
            return true
        end
        local f, l = lpegmatch(splitter,field)
        if f and l and fields[f] then
            return true -- language specific one
        end
    end

    local function found(dataset,tag,field,valid,fields)
        if valid == true then
         -- local fields = dataset.luadata[tag]
            local okay = fields[field]
            if okay then
                return field, okay
            end
            local details = dataset.details[tag]
            local value = details[field]
            if value then
                return field, value
            end
        elseif valid then
         -- local fields = dataset.luadata[tag]
            for i=1,#valid do
                local field = valid[i]
                local value = fields[field]
                if value then
                    return field, value
                end
            end
            local details = dataset.details[tag]
            for i=1,#valid do
                local value = details[field]
                if value then
                    return field, value
                end
            end
        end
    end

    local function get(dataset,tag,field,what,check,catspec) -- somewhat more extensive
        local current = rawget(datasets,dataset)
        if current then
            local data = current.luadata[tag]
            if data then
                local category = data.category
                local catspec  = (catspec or currentspecification).categories[category]
                if not catspec then
                    return false
                end
                local fields = catspec.fields
                if fields then
                    local sets = catspec.sets
                    if sets then
                        local set = sets[field]
                        if set then
                            if check then
                                for i=1,#set do
                                    local field = set[i]
                                    local kind  = (not check or data[field]) and fields[field]
                                    if kind then
                                        return what and kind or field
                                    end
                                end
                            elseif what then
                                local t = { }
                                for i=1,#set do
                                    t[i] = fields[set[i]] or "unknown"
                                end
                                return concat(t,",")
                            else
                                return concat(set,",")
                            end
                        end
                    end
                    local kind = (not check or data[field]) and fields[field]
                    if kind then
                        return what and kind or field
                    end
                end
            end
        end
        return ""
    end

    publications.permitted = permitted
    publications.found     = found
    publications.get       = get

    local function btxflush(name,tag,field)
        local dataset = rawget(datasets,name)
        if dataset then
            local fields = dataset.luadata[tag]
            if fields then
                local manipulator, field = splitmanipulation(field)
                local category = fields.category
                local valid    = permitted(category,field)
                if valid then
                    local name, value = found(dataset,tag,field,valid,fields)
                    if value then
                        typesetters[currentspecification.types[name]](field,value,manipulator)
                    elseif trace_detail then
                        report("%s %s %a in category %a for tag %a in dataset %a","unknown","entry",field,category,tag,name)
                    end
                elseif trace_detail then
                    report("%s %s %a in category %a for tag %a in dataset %a","invalid","entry",field,category,tag,name)
                end
            else
                report("unknown tag %a in dataset %a",tag,name)
            end
        else
            report("unknown dataset %a",name)
        end
    end

    local function btxfield(name,tag,field)
        local dataset = rawget(datasets,name)
        if dataset then
            local fields = dataset.luadata[tag]
            if fields then
                local category = fields.category
                local manipulator, field = splitmanipulation(field)
                if permitted(category,field) then
                    local value = fields[field]
                    if value then
                        typesetters[currentspecification.types[field]](field,value,manipulator)
                    elseif trace_detail then
                        report("%s %s %a in category %a for tag %a in dataset %a","unknown","field",field,category,tag,name)
                    end
                elseif trace_detail then
                    report("%s %s %a in category %a for tag %a in dataset %a","invalid","field",field,category,tag,name)
                end
            else
                report("unknown tag %a in dataset %a",tag,name)
            end
        else
            report("unknown dataset %a",name)
        end
    end

    local function btxdetail(name,tag,field)
        local dataset = rawget(datasets,name)
        if dataset then
            local fields = dataset.luadata[tag]
            if fields then
                local details = dataset.details[tag]
                if details then
                    local category = fields.category
                    local manipulator, field = splitmanipulation(field)
                    if permitted(category,field) then
                        local value = details[field]
                        if value then
                            typesetters[currentspecification.types[field]](field,value,manipulator)
                        elseif trace_detail then
                            report("%s %s %a in category %a for tag %a in dataset %a","unknown","detail",field,category,tag,name)
                        end
                    elseif trace_detail then
                        report("%s %s %a in category %a for tag %a in dataset %a","invalid","detail",field,category,tag,name)
                    end
                else
                    report("no details for tag %a in dataset %a",tag,name)
                end
            else
                report("unknown tag %a in dataset %a",tag,name)
            end
        else
            report("unknown dataset %a",name)
        end
    end

    local function btxdirect(name,tag,field)
        local dataset = rawget(datasets,name)
        if dataset then
            local fields = dataset.luadata[tag]
            if fields then
                local manipulator, field = splitmanipulation(field)
                local value = fields[field]
                if value then
                    context(typesetters.default(field,value,manipulator))
                elseif trace_detail then
                    report("field %a of tag %a in dataset %a has no value",field,tag,name)
                end
            else
                report("unknown tag %a in dataset %a",tag,name)
            end
        else
            report("unknown dataset %a",name)
        end
    end

    local function okay(name,tag,field)
        local dataset = rawget(datasets,name)
        if dataset then
            local fields = dataset.luadata[tag]
            if fields then
                local category = fields.category
                local valid    = permitted(category,field)
                if valid then
                    local value, field = found(dataset,tag,field,valid,fields)
                    return value and value ~= ""
                end
            end
        end
    end

    publications.okay = okay

    implement { name = "btxfield",     actions = btxfield,  arguments = "3 strings" }
    implement { name = "btxdetail",    actions = btxdetail, arguments = "3 strings" }
    implement { name = "btxflush",     actions = btxflush,  arguments = "3 strings" }
    implement { name = "btxdirect",    actions = btxdirect, arguments = "3 strings" }

    implement { name = "btxfieldname", actions = { get, context }, arguments = { "string", "string", "string", false, false } }
    implement { name = "btxfieldtype", actions = { get, context }, arguments = { "string", "string", "string", true,  false } }
    implement { name = "btxfoundname", actions = { get, context }, arguments = { "string", "string", "string", false, true  } }
    implement { name = "btxfoundtype", actions = { get, context }, arguments = { "string", "string", "string", true,  true  } }

    implement { name = "btxdoifelse",  actions = { okay, ctx_doifelse }, arguments = "3 strings" }
    implement { name = "btxdoif",      actions = { okay, ctx_doif     }, arguments = "3 strings" }
    implement { name = "btxdoifnot",   actions = { okay, ctx_doifnot  }, arguments = "3 strings" }

end

-- -- alternative approach: keep data at the tex end

function publications.singularorplural(singular,plural)
    if lastconcatsize and lastconcatsize > 1 then
        context(plural)
    else
        context(singular)
    end
end

-- loading

do

    local patterns = {
        "publ-imp-%s.mkvi",
        "publ-imp-%s.mkiv",
        "publ-imp-%s.tex",
    }

    local function failure(name)
        report("unknown library %a",name)
    end

    local function action(name,foundname)
        context.input(foundname)
    end

    function publications.loaddefinitionfile(name) -- a more specific name
        resolvers.uselibrary {
            name     = gsub(name,"^publ%-",""),
            patterns = patterns,
            action   = action,
            failure  = failure,
            onlyonce = true,
        }
    end

    local patterns = {
        "publ-imp-%s.lua",
    }

    function publications.loadreplacementfile(name) -- a more specific name
        resolvers.uselibrary {
            name     = gsub(name,"^publ%-",""),
            patterns = patterns,
            action   = publications.loaders.registercleaner,
            failure  = failure,
            onlyonce = true,
        }
    end

    implement { name = "btxloaddefinitionfile",  actions = publications.loaddefinitionfile,  arguments = "string" }
    implement { name = "btxloadreplacementfile", actions = publications.loadreplacementfile, arguments = "string" }

end

-- lists

local renderings = { } --- per dataset

do

    publications.lists = publications.lists or { }
    local lists        = publications.lists

    local context     = context
    local structures  = structures

    local references  = structures.references
    local sections    = structures.sections

    -- per rendering

    setmetatableindex(renderings,function(t,k)
        local v = {
            list         = { },
            done         = { },
            alldone      = { },
            used         = { },
            registered   = { },
            ordered      = { },
            shorts       = { },
            method       = v_none,
            texts        = setmetatableindex("table"),
            currentindex = 0,
        }
        t[k] = v
        return v
    end)

    -- helper

    function lists.register(dataset,tag,short) -- needs checking now that we split
        local r = renderings[dataset]
        if not short or short == "" then
            short = tag
        end
        if trace then
            report("registering publication entry %a with shortcut %a",tag,short)
        end
        local top = #r.registered + 1
        -- do we really need these
        r.registered[top] = tag
        r.ordered   [tag] = top
        r.shorts    [tag] = short
    end

    function lists.nofregistered(dataset)
        return #renderings[dataset].registered
    end

    local function validkeyword(dataset,tag,keyword,specification) -- todo: pass specification
        local kw = getcasted(dataset,tag,"keywords",specification)
        if kw then
            for i=1,#kw do
                if keyword[kw[i]] then
                    return true
                end
            end
        end
    end

    local function registerpage(pages,tag,result,listindex)
        local p = pages[tag]
        local r = result[listindex].references
        if p then
            local last = p[#p][2]
            local real = last.realpage
            if real ~= r.realpage then
                p[#p+1] = { listindex, r }
            end
        else
            pages[tag] = { { listindex, r } }
        end
    end

    -- tag | listindex | reference | userdata | dataindex

    local methods = { }
    lists.methods = methods

    methods[v_dataset] = function(dataset,rendering,keyword)
        local current = datasets[dataset]
        local luadata = current.luadata
        local list    = rendering.list
        for tag, data in sortedhash(luadata) do
            if not keyword or validkeyword(dataset,tag,keyword) then
                local index = data.index or 0
                list[#list+1] = { tag, index, 0, false, index }
            end
        end
    end

    -- todo: names = { "btx" }

    methods[v_force] = function (dataset,rendering,keyword)
        -- only for checking, can have duplicates, todo: collapse page numbers, although
        -- we then also needs deferred writes
        local result  = structures.lists.filter(rendering.specifications) or { }
        local list    = rendering.list
        local current = datasets[dataset]
        local luadata = current.luadata
        for listindex=1,#result do
            local r = result[listindex]
            local u = r.userdata -- better check on metadata.kind == "btx"
            if u then
                local set = u.btxset or v_default
                if set == dataset then
                    local tag = u.btxref
                    if tag and (not keyword or validkeyword(dataset,tag,keyword)) then
                        local data = luadata[tag]
                        list[#list+1] = { tag, listindex, 0, u, data and data.index or 0 }
                    end
                end
            end
        end
        lists.result = result
    end

    -- local  : if tag and                      done[tag] ~= section then ...
    -- global : if tag and not alldone[tag] and done[tag] ~= section then ...

    methods[v_local] = function(dataset,rendering,keyword)
        local result    = structures.lists.filter(rendering.specifications) or { }
        local section   = sections.currentid()
        local list      = rendering.list
        local repeated  = rendering.repeated == v_yes
        local r_done    = rendering.done
        local r_alldone = rendering.alldone
        local done      = repeated and { } or r_done
        local alldone   = repeated and { } or r_alldone
        local doglobal  = rendering.method == v_global
        local traced    = { } -- todo: only if interactive (backlinks) or when tracing
        local pages     = { }
        local current   = datasets[dataset]
        local luadata   = current.luadata
        -- handy for tracing :
        rendering.result = result
        --
        for listindex=1,#result do
            local r = result[listindex]
            local u = r.userdata
            if u then -- better check on metadata.kind == "btx"
                local set = u.btxset or v_default
                if set == dataset then
-- inspect(structures.references.internals[tonumber(u.btxint)])
                    local tag = u.btxref
                    if not tag then
                        -- problem
                    elseif done[tag] == section then -- a bit messy for global and all and so
                        -- skip
                    elseif doglobal and alldone[tag] then
                        -- skip
                    elseif not keyword or validkeyword(dataset,tag,keyword) then
                        if traced then
                            local l = traced[tag]
                            if l then
                                l[#l+1] = u.btxint -- tonumber ?
                            else
                                local data = luadata[tag]
                                local l = { tag, listindex, 0, u, data and data.index or 0 }
                                list[#list+1] = l
                                traced[tag] = l
                            end
                        else
                            done[tag]    = section
                            alldone[tag] = true
                            local data = luadata[tag]
                            list[#list+1] = { tag, listindex, 0, u, data and data.index or 0 }
                        end
                    end
                    if tag then
                        registerpage(pages,tag,result,listindex)
                    end
                end
            end
        end
        if traced then
            for tag in next, traced do
                done[tag]    = section
                alldone[tag] = true
            end
        end
        lists.result = result
        structures.lists.result = result
        rendering.pages = pages -- or list.pages
    end

    methods[v_global] = methods[v_local]

    function lists.collectentries(specification)
        local dataset = specification.dataset
        if not dataset then
            return
        end
        local rendering  = renderings[dataset]
        if not rendering then
            return
        end
        local method             = specification.method or v_none
        local ignored            = specification.ignored or ""
        local filter             = specification.filter or ""
        rendering.method         = method
        rendering.ignored        = ignored ~= "" and settings_to_set(ignored) or nil
        rendering.list           = { }
        rendering.done           = { }
        rendering.sorttype       = specification.sorttype or v_default
        rendering.criterium      = specification.criterium or v_none
        rendering.repeated       = specification.repeated or v_no
        rendering.group          = specification.group or ""
        rendering.specifications = specification
        local filtermethod       = methods[method]
        if not filtermethod then
            report_list("invalid method %a",method or "")
            return
        end
        report_list("collecting entries using method %a and sort order %a",method,rendering.sorttype)
        lists.result  = { } -- kind of reset
        local keyword = specification.keyword
        if keyword and keyword ~= "" then
            keyword = settings_to_set(keyword)
        else
            keyword = nil
        end
        filtermethod(dataset,rendering,keyword)
        local list = rendering.list
        if list and filter ~= "" then
            local find = publications.finder(dataset,filter)
            if find then
                local luadata = datasets[dataset].luadata
                local matched = 0
                for i=1,#list do
                    local found = list[i]
                    local entry = luadata[found[1]]
                    if find(entry) then
                        matched = matched + 1
                        list[matched] = found
                    end
                end
                for i=#list,matched + 1,-1 do
                    list[i] = nil
                end
            end
        end
        ctx_btxsetnoflistentries(list and #list or 0)
    end

    -- for determining width

    local groups = setmetatableindex("number")

    function lists.prepareentries(dataset)
        local rendering = renderings[dataset]
        local list      = rendering.list
        local used      = rendering.used
        local forceall  = rendering.criterium == v_all
        local repeated  = rendering.repeated == v_yes
        local sorttype  = rendering.sorttype or v_default
        local group     = rendering.group or ""
        local sorter    = lists.sorters[sorttype]
        local current   = datasets[dataset]
        local luadata   = current.luadata
        local details   = current.details
        local newlist   = { }
        local lastreferencenumber = groups[group] -- current.lastreferencenumber or 0
        for i=1,#list do
            local li    = list[i]
            local tag   = li[1]
            local entry = luadata[tag]
            if entry then
                if forceall or repeated or not used[tag] then
                    newlist[#newlist+1] = li
                    -- already here:
                    if not repeated then
                        used[tag] = true -- beware we keep the old state (one can always use criterium=all)
                    end
                end
            end
        end
        if type(sorter) == "function" then
            list = sorter(dataset,rendering,newlist,sorttype) or newlist
        else
            list = newlist
        end
        local newlist        = { }
        local tagtolistindex = { }
        rendering.tagtolistindex = tagtolistindex
        for i=1,#list do
            local li    = list[i]
            local tag   = li[1]
            local entry = luadata[tag]
            if entry then
                local detail = details[tag]
                if not detail then
                    -- fatal error
                    report("fatal error, missing details for tag %a in dataset %a (enhanced: %s)",tag,dataset,current.enhanced and "yes" or "no")
                 -- lastreferencenumber = lastreferencenumber + 1
                 -- details[tag] = { referencenumber = lastreferencenumber }
                 -- li[3] = lastreferencenumber
                 -- tagtolistindex[tag] = i
                 -- newlist[#newlist+1] = li
                elseif detail.parent then
                    -- skip this one
                else
                    local referencenumber = detail.referencenumber
                    if not referencenumber then
                        lastreferencenumber    = lastreferencenumber + 1
                        referencenumber        = lastreferencenumber
                        detail.referencenumber = lastreferencenumber
                    end
                    li[3] = referencenumber
                    tagtolistindex[tag] = i
                    newlist[#newlist+1] = li
                end
            end
        end
        groups[group] = lastreferencenumber
        rendering.list = newlist
    end

    function lists.fetchentries(dataset)
        local rendering = renderings[dataset]
        local list      = rendering.list
        if list then
            for i=1,#list do
                local li = list[i]
                ctx_btxsettag(li[1])
                ctx_btxsetnumber(li[3])
                ctx_btxchecklistentry()
            end
        end
    end

    -- for rendering

    -- setspecification

    local function btxflushpages(dataset,tag)
        -- todo: interaction
        local rendering = renderings[dataset]
        local pages     = rendering.pages
        if not pages then
            return
        else
            pages = pages[tag]
        end
        if not pages then
            return
        end
        local nofpages = #pages
        if nofpages == 0 then
            return
        end
        local first_p = nil
        local first_r = nil
        local last_p  = nil
        local last_r  = nil
        local ranges  = { }
        local nofdone = 0
        local function flush()
            if last_r and first_r ~= last_r then
                ranges[#ranges+1] = { first_p, last_p }
            else
                ranges[#ranges+1] = { first_p }
            end
        end
        for i=1,nofpages do
            local next_p = pages[i]
            local next_r = next_p[2].realpage
            if not first_r then
                first_p = next_p
                first_r = next_r
            elseif last_r + 1 == next_r then
                -- continue
            elseif first_r then
                flush()
                first_p = next_p
                first_r = next_r
            end
            last_p = next_p
            last_r = next_r
        end
        if first_r then
            flush()
        end
        local nofranges = #ranges
        for i=1,nofranges do
            local r = ranges[i]
            ctx_btxsetconcat(concatstate(i,nofranges))
            local first = r[1]
            local last  = r[2]
            ctx_btxsetfirstinternal(first[2].internal)
            ctx_btxsetfirstpage(first[1])
            if last then
                ctx_btxsetlastinternal(last[2].internal)
                ctx_btxsetlastpage(last[1])
            end
            if trace_detail then
                report("expanding page setup")
            end
            ctx_btxpagesetup("") -- nothing yet
        end
    end

    implement {
        name      = "btxflushpages",
        arguments = "2 strings",
        actions   = btxflushpages,
    }

    local function identical(a,b)
        local na = #a
        local nb = #b
        if na ~= nb then
            return false
        end
        if na > 0 then
            for i=1,na do
                if not identical(a[i],b[i]) then
                    return false
                end
            end
            return true
        end
        local ha = a.hash
        local hb = b.hash
        if ha then
            return ha == hb
        end
        for k, v in next, a do
            if k == "original" or k == "snippets" then
                -- skip diagnostic info
            elseif v ~= b[k] then
                return false
            end
        end
        return true
    end

    function lists.sameasprevious(dataset,i,name,order,method)
        local rendering = renderings[dataset]
        local list      = rendering.list
        local n         = tonumber(i)
        if n and n > 1 and n <= #list then
            local luadata   = datasets[dataset].luadata
            local p_index   = list[n-1][1]
            local c_index   = list[n  ][1]
            local previous  = getdirect(dataset,luadata[p_index],name)
            local current   = getdirect(dataset,luadata[c_index],name)

            -- authors are a special case

          -- if not order then
          --    order = gettexcounter("c_btx_list_reference")
          -- end
            if order and order > 0 and (method == v_always or method == v_doublesided) then
                local clist = listtolist[order]
                local plist = listtolist[order-1]
                if clist and plist then
                    local crealpage = clist.references.realpage
                    local prealpage = plist.references.realpage
                    if crealpage ~= prealpage then
                        if method == v_always or not conditionals.layoutisdoublesided then
                            if trace_detail then
                                report("previous %a, current %a, different page",previous,current)
                            end
                            return false
                        elseif crealpage % 2 == 0 then
                            if trace_detail then
                                report("previous %a, current %a, different page",previous,current)
                            end
                            return false
                        end
                    end
                end
            end
            local sameentry = false
            if current and current == previous then
                sameentry = true
            else
                local p_casted = getcasted(dataset,p_index,name)
                local c_casted = getcasted(dataset,c_index,name)
                if c_casted and c_casted == p_casted then
                    sameentry = true
                elseif type(c_casted) == "table" and type(p_casted) == "table" then
                    sameentry = identical(c_casted,p_casted)
                end
            end
            if trace_detail then
                if sameentry then
                    report("previous %a, current %a, same entry",previous,current)
                else
                    report("previous %a, current %a, different entry",previous,current)
                end
           end
            return sameentry
        else
            return false
        end
    end

    function lists.combiinlist(dataset,tag)
        local rendering = renderings[dataset]
        local list      = rendering.list
        local toindex   = rendering.tagtolistindex
        return toindex and toindex[tag]
    end

    function lists.flushcombi(dataset,tag)
        local rendering = renderings[dataset]
        local list      = rendering.list
        local toindex   = rendering.tagtolistindex
        local listindex = toindex and toindex[tag]
        if listindex then
            local li = list[listindex]
            if li then
                local data      = datasets[dataset]
                local luadata   = data.luadata
                local details   = data.details
                local tag       = li[1]
                local listindex = li[2]
                local n         = li[3]
                local entry     = luadata[tag]
                local detail    = details[tag]
                ctx_btxstartcombientry()
                ctx_btxsetcurrentlistindex(listindex)
                ctx_btxsetcategory(entry.category or "unknown")
                ctx_btxsettag(tag)
                ctx_btxsetnumber(n)
                local language = entry.language
                if language then
                    ctx_btxsetlanguage(language)
                end
                local authorsuffix = detail.authorsuffix
                if authorsuffix then
                    ctx_btxsetsuffix(authorsuffix)
                end
                ctx_btxhandlecombientry()
                ctx_btxstopcombientry()
            end
        end
    end

    function lists.flushtag(dataset,i)
        local li = renderings[dataset].list[i]
        ctx_btxsettag(li and li[1] or "")
    end

    function lists.flushentry(dataset,i)
        local rendering = renderings[dataset]
        local list      = rendering.list
        local li        = list[i]
        if li then
            local data      = datasets[dataset]
            local luadata   = data.luadata
            local details   = data.details
            local tag       = li[1]
            local listindex = li[2]
            local n         = li[3]
            local entry     = luadata[tag]
            local detail    = details[tag]
            --
            ctx_btxstartlistentry()
            ctx_btxsetcurrentlistentry(i) -- redundant
            ctx_btxsetcurrentlistindex(listindex or 0)
            local children = detail.children
            local language = entry.language
            if children then
                ctx_btxsetcombis(concat(children,","))
            end
            ctx_btxsetcategory(entry.category or "unknown")
            ctx_btxsettag(tag)
            ctx_btxsetnumber(n)
            --
            local citation = citetolist[n]
            if citation then
                local references = citation.references
                if references then
                    local internal = references.internal
                    if internal and internal > 0 then
                        ctx_btxsetinternal(internal)
                    end
                end
            end
            --
            if language then
                ctx_btxsetlanguage(language)
            end
            local userdata = li[4]
            if userdata then
                local b = userdata.btxbtx
                local a = userdata.btxatx
                if b then
                    ctx_btxsetbefore(b)
                end
                if a then
                    ctx_btxsetafter(a)
                end
                local bl = userdata.btxint
                if bl and bl ~= "" then
                    ctx_btxsetbacklink(bl)
                end
            end
            local authorsuffix = detail.authorsuffix
            if authorsuffix then
                ctx_btxsetsuffix(authorsuffix)
            end
            rendering.userdata = userdata
            ctx_btxhandlelistentry()
            ctx_btxstoplistentry()
            --
         -- context(function()
         --     -- wrapup
         --     rendering.ignoredfields = nil
         -- end)
        end
    end

    local function getuserdata(dataset,key)
        local rendering = renderings[dataset]
        if rendering then
            local userdata = rendering.userdata
            if userdata then
                local value = userdata[key]
                if value and value ~= "" then
                    return value
                end
            end
        end
    end

    lists.uservariable = getuserdata

    function lists.filterall(dataset)
        local r = renderings[dataset]
        local list = r.list
        local registered = r.registered
        for i=1,#registered do
            list[i] = { registered[i], i, 0, false, false }
        end
    end

    implement {
        name      = "btxuservariable",
        arguments = "2 strings",
        actions   = { getuserdata, context },
    }

    implement {
        name      = "btxdoifelseuservariable",
        arguments = "2 strings",
        actions   = { getuserdata, ctx_doifelse },
    }

 -- implement {
 --     name      = "btxresolvelistreference",
 --     arguments = "2 strings",
 --     actions   = lists.resolve,
 -- }

    implement {
        name      = "btxcollectlistentries",
        actions   = lists.collectentries,
        arguments = {
            {
                { "names" },
                { "criterium" },
                { "reference" },
                { "method" },
                { "dataset" },
                { "keyword" },
                { "sorttype" },
                { "repeated" },
                { "ignored" },
                { "group" },
                { "filter" },
            }
        }
    }

    implement {
        name      = "btxpreparelistentries",
        arguments = "string",
        actions   = lists.prepareentries,
    }

    implement {
        name      = "btxfetchlistentries",
        arguments = "string",
        actions   = lists.fetchentries,
    }

    implement {
        name      = "btxflushlistentry",
        arguments = { "string", "integer" },
        actions   = lists.flushentry,
    }

    implement {
        name      = "btxflushlisttag",
        arguments = { "string", "integer" },
        actions   = lists.flushtag,
    }

    implement {
        name      = "btxflushlistcombi",
        arguments = "2 strings",
        actions   = lists.flushcombi,
    }

    implement {
        name      = "btxdoifelsesameasprevious",
        actions   = { lists.sameasprevious, ctx_doifelse },
        arguments = { "string", "integer", "string", "integer", "string" }
    }

    implement {
        name      = "btxdoifelsecombiinlist",
        arguments = "2 strings",
        actions   = { lists.combiinlist, ctx_doifelse },
    }

end

do

    local citevariants        = { }
    publications.citevariants = citevariants

    local function btxvalidcitevariant(dataset,variant)
        local citevariant = rawget(citevariants,variant)
        if citevariant then
            return citevariant
        end
        local s = datasets[dataset]
        if s then
            s = s.specifications
        end
        if s then
            for k, v in sortedhash(s) do
                s = k
                break
            end
        end
        if s then
            s = specifications[s]
        end
        if s then
            s = s.types
        end
        if s then
            variant = s[variant]
            if variant then
                citevariant = rawget(citevariants,variant)
            end
            if citevariant then
                return citevariant
            end
        end
        return citevariants.default
    end

    local function btxhandlecite(specification)
        local dataset   = specification.dataset or v_default
        local reference = specification.reference
        local variant   = specification.variant
        --
        if not variant or variant == "" then
            variant = "default"
        end
        if not reference or reference == "" then
            return
        end
        --
        local data = datasets[dataset]
        if not data.suffixed then
            data.authorconversion = specification.authorconversion
            publications.enhancers.suffixes(data)
        end
        --
        specification.variant   = variant
        specification.compress  = specification.compress
        specification.markentry = specification.markentry ~= false
        --
        if specification.sorttype == v_yes then
            specification.sorttype = v_normal
        end
        --
        local prefix, rest = lpegmatch(prefixsplitter,reference)
        if prefix and rest then
            dataset = prefix
            specification.dataset   = prefix
            specification.reference = rest
        end
        --
        if trace_cite then
            report_cite("inject, dataset: %s, tag: %s, variant: %s, compressed",
                specification.dataset or "-",
                specification.reference,
                specification.variant
            )
        end
        --
        ctx_btxsetdataset(dataset)
        --
        local citevariant = btxvalidcitevariant(dataset,variant)
        --
        citevariant(specification) -- we always fall back on default
    end

    local function btxhandlenocite(specification)
        if trialtypesetting() then
            return
        end
        local dataset   = specification.dataset or v_default
        local reference = specification.reference
        if not reference or reference == "" then
            return
        end
        --
        local method   = specification.method
        local internal = specification.internal or ""
        --
        local prefix, rest = lpegmatch(prefixsplitter,reference)
        if rest then
            dataset   = prefix
            reference = rest
        end
        --
        if trace_cite then
            report_cite("mark, dataset: %s, tags: %s",dataset or "-",reference)
        end
        --
        local reference = publications.parenttag(dataset,reference)
        --
        local found, todo, list = findallused(dataset,reference,internal)
        --
        if todo then
            marked_todo    = todo
            marked_dataset = dataset
            marked_list    = list
            marked_method  = method
            btxflushmarked() -- here (could also be done in caller)
        else
            marked_todo = false
        end
    end

    implement {
        name      = "btxhandlecite",
        actions   = btxhandlecite,
        arguments = {
            {
                { "dataset" },
                { "reference" },
                { "method" },
                { "variant" },
                { "sorttype" },
                { "compress" },
                { "authorconversion" },
                { "author" },
                { "lefttext" },
                { "righttext" },
                { "before" },
                { "after" },
            }
        }
    }

    implement {
        name      = "btxhandlenocite",
        actions   = btxhandlenocite,
        arguments = {
            {
                { "dataset" },
                { "reference" },
                { "method" },
            }
        }
    }

    -- sorter

    local keysorter = function(a,b)
        local ak = a.sortkey
        local bk = b.sortkey
        if ak == bk then
            local as = a.suffix -- numeric
            local bs = b.suffix -- numeric
            if as and bs then
                return (as or 0) < (bs or 0)
            else
                return false
            end
        else
            return ak < bk
        end
    end

    local revsorter = function(a,b)
        return keysorter(b,a)
    end

    local function compresslist(source,specification)
        if specification.sorttype == v_normal then
            sort(source,keysorter)
        elseif specification.sorttype == v_reverse then
            sort(source,revsorter)
        end
        if specification and specification.compress == v_yes and specification.numeric then
            local first, last, firstr, lastr
            local target, noftarget, tags = { }, 0, { }
            local oldvalue = nil
            local function flushrange()
                noftarget = noftarget + 1
                if last > first + 1 then
                    target[noftarget] = {
                        first = firstr,
                        last  = lastr,
                        tags  = tags,
                    }
                else
                    target[noftarget] = firstr
                    if last > first then
                        noftarget = noftarget + 1
                        target[noftarget] = lastr
                    end
                end
                tags = { }
            end
            for i=1,#source do
                local entry   = source[i]
                local current = entry.sortkey -- so we need a sortkey !
                if type(current) == "number" then
                    if entry.suffix then
                        if not first then
                            first, last, firstr, lastr = current, current, entry, entry
                        else
                            flushrange()
                            first, last, firstr, lastr = current, current, entry, entry
                        end
                    else
                        if not first then
                            first, last, firstr, lastr = current, current, entry, entry
                        elseif current == last + 1 then
                            last, lastr = current, entry
                        else
                            flushrange()
                            first, last, firstr, lastr = current, current, entry, entry
                        end
                    end
                    tags[#tags+1] = entry.tag
                end
            end
            if first and last then
                flushrange()
            end
            return target
        else
            local target, noftarget = { }, 0
            for i=1,#source do
                local entry = source[i]
                noftarget   = noftarget + 1
                target[noftarget] = {
                    first = entry,
                    tags  = { entry.tag },
                }
            end
            return target
        end
    end

    -- local source = {
    --     { tag = "one",   internal = 1, value = "foo", page = 1 },
    --     { tag = "two",   internal = 2, value = "bar", page = 2 },
    --     { tag = "three", internal = 3, value = "gnu", page = 3 },
    -- }
    --
    -- local target = compresslist(source)

    local numberonly = R("09")^1 / tonumber + P(1)^0
    local f_missing  = formatters["<%s>"]

    -- maybe also sparse (e.g. pages)

    -- a bit redundant access to datasets

    local function processcite(presets,specification)
        --
        if specification then
            setmetatableindex(specification,presets)
        else
            specification = presets
        end
        --
        local dataset    = specification.dataset
        local reference  = specification.reference
        local internal   = specification.internal
        local setup      = specification.variant
        local compress   = specification.compress
        local sorttype   = specification.sorttype
        local getter     = specification.getter
        local setter     = specification.setter
        local compressor = specification.compressor
        local method     = specification.method
        local varfield   = specification.varfield
        --
        local reference  = publications.parenttag(dataset,reference)
        --
        local found, todo, list = findallused(dataset,reference,internal,method == v_text or method == v_always) -- also when not in list
        --
        if not found or #found == 0 then
--         if not list or #list == 0 then
            report("no entry %a found in dataset %a",reference,dataset)
        elseif not setup then
            report("invalid reference for %a",reference)
        else
            if trace_cite then
                report("processing reference %a",reference)
            end
            local source  = { }
            local luadata = datasets[dataset].luadata
            for i=1,#found do
                local entry      = found[i]
                local userdata   = entry.userdata
                local references = entry.references
                local tag        = userdata and userdata.btxref or entry.tag -- no need for userdata
                if tag then
                    local ldata = luadata[tag]
                    local data  = {
                        internal  = references and references.internal,
                        language  = ldata.language,
                        dataset   = dataset,
                        tag       = tag,
                        varfield  = varfield,
                     -- combis    = entry.userdata.btxcom,
                     -- luadata   = ldata,
                    }
                    setter(data,dataset,tag,entry)
                    if type(data) == "table" then
                        source[#source+1] = data
                    else
                        report("error in cite rendering %a",setup or "?")
                    end
                end
            end

            local lefttext  = specification.lefttext
            local righttext = specification.righttext
            local before    = specification.before
            local after     = specification.after

            if lefttext  and lefttext  ~= "" then lefttext  = settings_to_array(lefttext)  end
            if righttext and righttext ~= "" then righttext = settings_to_array(righttext) end
            if before    and before    ~= "" then before    = settings_to_array(before)    end
            if after     and after     ~= "" then after     = settings_to_array(after)     end

            local function flush(i,n,entry,last)
                local tag = entry.tag
                local currentcitation = markcite(dataset,tag)
                --
                ctx_btxstartcite()
                ctx_btxsettag(tag)
                ctx_btxsetcategory(entry.category or "unknown")
                --
                local language = entry.language
                if language then
                    ctx_btxsetlanguage(language)
                end
                --
                if lefttext  then local text = lefttext [i] ; if text and text ~= "" then ctx_btxsetlefttext (text) end end
                if righttext then local text = righttext[i] ; if text and text ~= "" then ctx_btxsetrighttext(text) end end
                if before    then local text = before   [i] ; if text and text ~= "" then ctx_btxsetbefore   (text) end end
                if after     then local text = after    [i] ; if text and text ~= "" then ctx_btxsetafter    (text) end end
                --
                if method ~= v_text then
                    ctx_btxsetbacklink(currentcitation)
                    local bl = listtocite[currentcitation]
                    if bl then
                        -- we refer to a coming list entry
                        bl = bl.references.internal
                    else
                        -- we refer to a previous list entry
                        bl = entry.internal
                    end
                    ctx_btxsetinternal(bl and bl > 0 and bl or "")
                end
                local language = entry.language
                if language then
                    ctx_btxsetlanguage(language)
                end
             -- local combis = entry.combis
             -- if combis then
             --     ctx_btxsetcombis(combis)
             -- end
                if not getter(entry,last,nil,specification) then
                    ctx_btxsetfirst("") -- (f_missing(tag))
                end
                ctx_btxsetconcat(concatstate(i,n))
                if trace_detail then
                    report("expanding cite setup %a",setup)
                end
                ctx_btxcitesetup(setup)
                ctx_btxstopcite()
            end
            if sorttype == v_normal or sorttype == v_reverse then
                local target = (compressor or compresslist)(source,specification)
                local nofcollected = #target
                if nofcollected == 0 then
                    local nofcollected = #source
                    if nofcollected == 0 then
                        unknowncite(reference)
                    else
                        for i=1,nofcollected do
                            flush(i,nofcollected,source[i])
                        end
                    end
                else
                    for i=1,nofcollected do
                        local entry = target[i]
                        local first = entry.first
                        if first then
                            flush(i,nofcollected,first,entry.last)
                        else
                            flush(i,nofcollected,entry)
                        end
                    end
                end
            else
                local nofcollected = #source
                if nofcollected == 0 then
                    unknowncite(reference)
                else
                    for i=1,nofcollected do
                        flush(i,nofcollected,source[i])
                    end
                end
            end
        end
        if trialtypesetting() then
            marked_todo = false
        elseif method ~= v_text then
            marked_todo    = todo
            marked_dataset = dataset
            marked_list    = list
            marked_method  = method
            btxflushmarked() -- here (could also be done in caller)
        else
            marked_todo = false
        end
    end

    --

    local function simplegetter(first,last,field,specification)
        local value = first[field]
        if value then
            if type(value) == "string" then
                ctx_btxsetfirst(value)
                if last then
                    ctx_btxsetsecond(last[field])
                end
                return true
            else
                report("missing data type definition for %a",field)
            end
        end
    end

    local setters = setmetatableindex({},function(t,k)
        local v = function(data,dataset,tag,entry)
            local value  = getcasted(dataset,tag,k)
            data.value   = value -- not really needed
            data[k]      = value
            data.sortkey = value
            data.sortfld = k
        end
        t[k] = v
        return v
    end)

    local getters = setmetatableindex({},function(t,k)
        local v = function(first,last,_,specification)
            return simplegetter(first,last,k,specification) -- maybe _ or k
        end
        t[k] = v
        return v
    end)

    setmetatableindex(citevariants,function(t,k)
        local p = defaultvariant or "default"
        local v = rawget(t,p)
        report_cite("variant %a falls back on %a setter and getter with setup %a",k,p,k)
        t[k] = v
        return v
    end)

    function citevariants.default(presets)
        local variant = presets.variant
        processcite(presets,{
            setup   = variant,
            setter  = setters[variant],
            getter  = getters[variant],
        })
    end

    -- category

    do

        local function setter(data,dataset,tag,entry)
            data.category = getfield(dataset,tag,"category")
        end

        local function getter(first,last,_,specification)
            return simplegetter(first,last,"category",specification)
        end

        function citevariants.category(presets)
            processcite(presets,{
                setter  = setter,
                getter  = getter,
            })
        end

    end


    -- entry (we could provide a generic one)

    do

        local function setter(data,dataset,tag,entry)
            -- nothing
        end

        local function getter(first,last,_,specification) -- last not used
            ctx_btxsetfirst(first.tag)
        end

        function citevariants.entry(presets)
            processcite(presets,{
                compress = false,
                setter   = setter,
                getter   = getter,
            })
        end

    end

    -- short

    do

        local function setter(data,dataset,tag,entry)
            local short  = getdetail(dataset,tag,"shorthash")
            local suffix = getdetail(dataset,tag,"shortsuffix")
            data.short   = short
            data.sortkey = short
            data.suffix  = suffix
        end

        local function getter(first,last,_,specification) -- last not used
            local short = first.short
            if short then
                local suffix = first.suffix
                ctx_btxsetfirst(short)
                if suffix then
                    ctx_btxsetsuffix(suffix) -- watch out: third
                end
                return true
            end
        end

        function citevariants.short(presets)
            processcite(presets,{
                setter = setter,
                getter = getter,
            })
        end

    end

    -- pages (no compress)

    do

        local function setter(data,dataset,tag,entry)
            data.pages = getcasted(dataset,tag,"pages")
        end

        local function getter(first,last,_,specification)
            local pages = first.pages
            if pages then
                if type(pages) == "table" then
                    ctx_btxsetfirst(pages[1])
                    ctx_btxsetsecond(pages[2])
                else
                    ctx_btxsetfirst(pages)
                end
                return true
            end
        end

        function citevariants.page(presets)
            processcite(presets,{
                setter = setter,
                getter = getter,
            })
        end

    end

    -- num

    do

        local function setter(data,dataset,tag,entry)
            local entries = entry.entries
            local text    = entries and entries.text or "?"
            data.num      = text
            data.sortkey  = tonumber(text) or text
        end

        local function getter(first,last,tag,specification)
            return simplegetter(first,last,"num",specification)
        end

        function citevariants.num(presets)
            processcite(presets,{
                numeric = true,
                setter  = setter,
                getter  = getter,
            })
        end

        citevariants.textnum = citevariants.num -- should not be needed

    end

    -- year

    do

        local function setter(data,dataset,tag,entry)
            local year   = getfield (dataset,tag,"year")
            local suffix = getdetail(dataset,tag,"authorsuffix")
            data.year    = year
            data.suffix  = suffix
            data.sortkey = tonumber(year) or 9999
        end

        local function getter(first,last,_,specification)
            return simplegetter(first,last,"year",specification)
        end

        function citevariants.year(presets)
            processcite(presets,{
                numeric = true,
                setter  = setter,
                getter  = getter,
            })
        end

    end

    -- index

    do

        local function setter(data,dataset,tag,entry)
            local index  = getfield(dataset,tag,"index")
            data.index   = index
            data.sortkey = index
        end

        local function getter(first,last,_,specification)
            return simplegetter(first,last,"index",specification)
        end

        function citevariants.index(presets)
            processcite(presets,{
                setter  = setter,
                getter  = getter,
                numeric = true,
            })
        end

    end

    -- tag

    do

        local function setter(data,dataset,tag,entry)
            data.tag     = tag
            data.sortkey = tag
        end

        local function getter(first,last,_,specification)
            return simplegetter(first,last,"tag",specification)
        end

        function citevariants.tag(presets)
            return processcite(presets,{
                setter = setter,
                getter = getter,
            })
        end

    end

    -- keyword

    do

        local function listof(list)
            local size = type(list) == "table" and #list or 0
            if size > 0 then
                return function()
                    for i=1,size do
                        ctx_btxsetfirst(list[i])
                        ctx_btxsetconcat(concatstate(i,size))
                        ctx_btxcitesetup("listelement")
                    end
                    return true
                end
            else
                return "?" -- unknown
            end
        end

        local function setter(data,dataset,tag,entry)
            data.keywords = getcasted(dataset,tag,"keywords")
        end

        local function getter(first,last,_,specification)
            context(listof(first.keywords))
        end

        function citevariants.keywords(presets)
            return processcite(presets,{
                variant = "keywords",
                setter  = setter,
                getter  = getter,
            })
        end

    end

    -- authors

    do

        -- is this good enough?

        local keysorter = function(a,b)
            local ak = a.authorhash
            local bk = b.authorhash
            if ak == bk then
                local as = a.authorsuffix -- numeric
                local bs = b.authorsuffix -- numeric
                if as and bs then
                    return (as or 0) < (bs or 0)
                else
                    return false
                end
            elseif ak and bk then
                return ak < bk
            else
                return false
            end
        end

        local revsorter = function(a,b)
            return keysorter(b,a)
        end

        local function authorcompressor(found,specification)
            -- HERE
            if specification.sorttype == v_normal then
                sort(found,keysorter)
            elseif specification.sorttype == v_reverse then
                sort(found,revsorter)
            end
            local result  = { }
            local entries = { }
            for i=1,#found do
                local entry  = found[i]
                local author = entry.authorhash
                if author then
                    local aentries = entries[author]
                    if aentries then
                        aentries[#aentries+1] = entry
                    else
                        entries[author] = { entry }
                    end
                end
            end
            -- beware: we use tables as hash so we get a cycle when inspecting (unless we start
            -- hashing with strings)
            for i=1,#found do
                local entry  = found[i]
                local author = entry.authorhash
                if author then
                    local aentries = entries[author]
                    if not aentries then
                        result[#result+1] = entry
                    elseif aentries == true then
                        -- already done
                    else
                        result[#result+1] = entry
                        entry.entries = aentries
                        entries[author] = true
                    end
                end
            end
            return result
        end

        local function authorconcat(target,key,setup)
            ctx_btxstartsubcite(setup)
            local nofcollected = #target
            if nofcollected == 0 then
                unknowncite(tag)
            else
                for i=1,nofcollected do
                    local entry = target[i]
                    local first = entry.first
                    local tag   = entry.tag
                    local currentcitation = markcite(entry.dataset,tag)
                    ctx_btxstartciteauthor()
                    ctx_btxsettag(tag)
                    ctx_btxsetbacklink(currentcitation)
                    local bl = listtocite[currentcitation]
                    ctx_btxsetinternal(bl and bl.references.internal or "")
                    if first then
                        ctx_btxsetfirst(first[key] or "") -- f_missing(first.tag))
                        local suffix = entry.suffix
                        local last   = entry.last
                        local value  = last and last[key]
                        if value then
                            ctx_btxsetsecond(value)
                        end
                        if suffix then
                            ctx_btxsetsuffix(suffix)
                        end
                    else
                        local suffix = entry.suffix
                        local value  = entry[key] or "" -- f_missing(tag)
                        ctx_btxsetfirst(value)
                        if suffix then
                            ctx_btxsetsuffix(suffix)
                        end
                    end
                    ctx_btxsetconcat(concatstate(i,nofcollected))
                    if trace_detail then
                        report("expanding %a cite setup %a","multiple author",setup)
                    end
                    ctx_btxsubcitesetup(setup)
                    ctx_btxstopciteauthor()
                end
            end
            ctx_btxstopsubcite()
        end

        local function authorsingle(entry,key,setup)
            ctx_btxstartsubcite(setup)
            ctx_btxstartciteauthor()
            local tag = entry.tag
            ctx_btxsettag(tag)
            ctx_btxsetfirst(entry[key] or "") -- f_missing(tag)
            if suffix then
                ctx_btxsetsuffix(entry.suffix)
            end
            if trace_detail then
                report("expanding %a cite setup %a","single author",setup)
            end
            ctx_btxcitesetup(setup)
            ctx_btxstopciteauthor()
            ctx_btxstopsubcite()
        end

        local partialinteractive = false

        local currentbtxciteauthor = function()
            context.currentbtxciteauthorbyfield()
            return true -- needed?
        end

        local function authorgetter(first,last,key,specification) -- only first
            ctx_btxsetauthorfield(first.varfield or "author")
            if first.type == "author" then
                ctx_btxsetfirst(currentbtxciteauthor) -- formatter (much slower)
            else
                ctx_btxsetfirst(first.author)         -- unformatted
            end
            local entries = first.entries
            -- alternatively we can use a concat with one ... so that we can only make the
            -- year interactive, as with the concat
            if partialinteractive and not entries then
                entries = { first }
            end
            if entries then
                -- happens with year
                local c = compresslist(entries,specification)
                local f = function() authorconcat(c,key,specification.setup or "author") return true end -- indeed return true?
                ctx_btxsetcount(#c)
                ctx_btxsetsecond(f)
            elseif first then
                -- happens with num
                local f = function() authorsingle(first,key,specification.setup or "author") return true end -- indeed return true?
                ctx_btxsetcount(0)
                ctx_btxsetsecond(f)
            end
            return true
        end

        -- author (the varfield hack is for editor and translator i.e author type)

        local function setter(data,dataset,tag,entry)
            data.author, data.field, data.type = getcasted(dataset,tag,data.varfield or "author")
            data.sortkey = text and lpegmatch(numberonly,text)
            data.authorhash = getdetail(dataset,tag,"authorhash") -- todo let getcasted return
        end

        local function getter(first,last,_,specification)
            ctx_btxsetauthorfield(specification.varfield or "author")
            if first.type == "author" then
                ctx_btxsetfirst(currentbtxciteauthor) -- formatter (much slower)
            else
                ctx_btxsetfirst(first.author)         -- unformatted
            end
            return true
        end

        function citevariants.author(presets)
            processcite(presets,{
                variant    = "author",
                setup      = "author",
                setter     = setter,
                getter     = getter,
                varfield   = presets.variant or "author",
                compressor = authorcompressor,
            })
        end

        -- authornum

        local function setter(data,dataset,tag,entry)
            local entries = entry.entries
            local text    = entries and entries.text or "?"
            data.author, data.field, data.type = getcasted(dataset,tag,"author")
            data.authorhash = getdetail(dataset,tag,"authorhash") -- todo let getcasted return
            data.num     = text
            data.sortkey = text and lpegmatch(numberonly,text)
        end

        local function getter(first,last,_,specification)
            authorgetter(first,last,"num",specification)
            return true
        end

        function citevariants.authornum(presets)
            processcite(presets,{
                variant    = "authornum",
                setup      = "author:num",
                numeric    = true,
                setter     = setter,
                getter     = getter,
                compressor = authorcompressor,
            })
        end

        -- authoryear | authoryears

        local function setter(data,dataset,tag,entry)
            data.author, data.field, data.type = getcasted(dataset,tag,"author")
            data.authorhash = getdetail(dataset,tag,"authorhash") -- todo let getcasted return
            local year   = getfield (dataset,tag,"year")
            local suffix = getdetail(dataset,tag,"authorsuffix")
            data.year    = year
            data.suffix  = suffix
            data.sortkey = tonumber(year) or 9999
        end

        local function getter(first,last,_,specification)
            authorgetter(first,last,"year",specification)
            return true
        end

        function citevariants.authoryear(presets)
            processcite(presets,{
                variant    = "authoryear",
                setup      = "author:year",
                numeric    = true,
                setter     = setter,
                getter     = getter,
                compressor = authorcompressor,
            })
        end

        local function getter(first,last,_,specification)
            authorgetter(first,last,"year",specification)
            return true
        end

        function citevariants.authoryears(presets)
            processcite(presets,{
                variant    = "authoryears",
                setup      = "author:years",
                numeric    = true,
                setter     = setter,
                getter     = getter,
                compressor = authorcompressor,
            })
        end

    end

end

-- List variants

do

    local listvariants        = { }
    publications.listvariants = listvariants

    local function btxlistvariant(dataset,block,tag,variant,listindex)
        local action = listvariants[variant] or listvariants.default
        if action then
            listindex = tonumber(listindex)
            if listindex then
                action(dataset,block,tag,variant,listindex)
            end
        end
    end

    implement {
        name      = "btxlistvariant",
        arguments = "5 strings",
        actions   = btxlistvariant,
    }

    function listvariants.default(dataset,block,tag,variant)
        ctx_btxsetfirst("?")
        if trace_detail then
            report("expanding %a list setup %a","default",variant)
        end
        ctx_btxnumberingsetup("default")
    end

    function listvariants.num(dataset,block,tag,variant,listindex)
        ctx_btxsetfirst(listindex)
        if trace_detail then
            report("expanding %a list setup %a","num",variant)
        end
        ctx_btxnumberingsetup(variant or "num")
    end

 -- listvariants[v_yes] = listvariants.num

    function listvariants.index(dataset,block,tag,variant,listindex)
        local index = getdetail(dataset,tag,"index")
        ctx_btxsetfirst(index or "?")
        if trace_detail then
            report("expanding %a list setup %a","index",variant)
        end
        ctx_btxnumberingsetup(variant or "index")
    end

    function listvariants.tag(dataset,block,tag,variant,listindex)
        ctx_btxsetfirst(tag)
        if trace_detail then
            report("expanding %a list setup %a","tag",variant)
        end
        ctx_btxnumberingsetup(variant or "tag")
    end

    function listvariants.short(dataset,block,tag,variant,listindex)
        local short  = getdetail(dataset,tag,"shorthash")
        local suffix = getdetail(dataset,tag,"shortsuffix")
        if short then
            ctx_btxsetfirst(short)
        end
        if suffix then
            ctx_btxsetsuffix(suffix)
        end
        if trace_detail then
            report("expanding %a list setup %a","short",variant)
        end
        ctx_btxnumberingsetup(variant or "short")
    end

end

-- a helper

do

 -- local context   = context
 -- local lpegmatch = lpeg.match
    local splitter  = lpeg.tsplitat(":")

    implement {
        name      = "checkinterfacechain",
        arguments = "2 strings",
        actions   = function(str,command)
            local chain = lpegmatch(splitter,str)
            if #chain > 0 then
                local command = context[command]
                local parent  = ""
                local child   = chain[1]
                command(child,parent)
                for i=2,#chain do
                    parent = child
                    child  = child .. ":" .. chain[i]
                    command(child,parent)
                end
            end
        end
    }

end

do

    local btxstring = ""

    implement {
        name    = "btxcmdstring",
        actions = function() if btxstring ~= "" then context(btxstring) end end,
    }

    function publications.prerollcmdstring(str)
        btxstring = str or ""
        tex.runtoks("t_btx_cmd")
        return nodes.toutf(tex.getbox("b_btx_cmd").list) or str
    end

end