summaryrefslogtreecommitdiff
path: root/Build/source/texk/gregorio/gregorio-src/src/gregoriotex/gregoriotex-write.c
blob: ae394a33c10b402e191a52154374c45dd9358b0d (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
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
/*
 * Gregorio is a program that translates gabc files to GregorioTeX
 * This file contains functions for writing GregorioTeX from Gregorio structures.
 *
 * Copyright (C) 2008-2021 The Gregorio Project (see CONTRIBUTORS.md)
 *
 * This file is part of Gregorio.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>. */

/**
 * @file
 * @brief The plugin which writes a GregorioTeX score.
 */

#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include "bool.h"
#include "struct.h"
#include "unicode.h"
#include "messages.h"
#include "characters.h"
#include "plugins.h"
#include "support.h"
#include "utf8strings.h"

#include "gregoriotex.h"

#define BUFSIZE 128

/* a structure containing the status */
typedef struct gregoriotex_status {
    bool point_and_click;

    /* true if the current_glyph will have an additional line under or not
     * (useful to determine the length of the bar in case of a flexa starting
     * at d */
    bool bottom_line;

    signed char top_height;
    signed char bottom_height;

    /* indicates if there is a translation on the line */
    bool translation;

    /* indicates if there is "above lines text" on the line */
    bool abovelinestext;

    bool suppressed_custos;
} gregoriotex_status;

#define UNDETERMINED_HEIGHT -127

#define MAX_AMBITUS 5
static const char *tex_ambitus[] = {
    "", "One", "Two", "Three", "Four", "Five"
};

#define SHAPE(NAME) static const char *const SHAPE_##NAME = #NAME
SHAPE(Ancus);
SHAPE(AncusLongqueue);
SHAPE(AscendensOriscus);
SHAPE(AscendensOriscusLineBL);
SHAPE(AscendensOriscusLineTL);
SHAPE(AscendensOriscusScapus);
SHAPE(AscendensOriscusScapusLongqueue);
SHAPE(AscendensOriscusScapusOpenqueue);
SHAPE(AscendensPunctumInclinatum);
SHAPE(DescendensOriscus);
SHAPE(DescendensOriscusLineBL);
SHAPE(DescendensOriscusLineTL);
SHAPE(DescendensOriscusScapus);
SHAPE(DescendensOriscusScapusLongqueue);
SHAPE(DescendensOriscusScapusOpenqueue);
SHAPE(DescendensPunctumInclinatum);
SHAPE(Flat);
SHAPE(FlatParen);
SHAPE(Flexus);
SHAPE(FlexusLongqueue);
SHAPE(FlexusNobar);
SHAPE(FlexusOpenqueue);
SHAPE(FlexusOriscus);
SHAPE(FlexusOriscusInusitatus);
SHAPE(FlexusOriscusScapus);
SHAPE(FlexusOriscusScapusInusitatus);
SHAPE(FlexusOriscusScapusInusitatusLongqueue);
SHAPE(FlexusOriscusScapusInusitatusOpenqueue);
SHAPE(FlexusOriscusScapusLongqueue);
SHAPE(FlexusOriscusScapusOpenqueue);
SHAPE(Linea);
SHAPE(LineaPunctum);
SHAPE(Natural);
SHAPE(NaturalParen);
SHAPE(OriscusDeminutus);
SHAPE(Pes);
SHAPE(PesAscendensOriscus);
SHAPE(PesDescendensOriscus);
SHAPE(PesQuadratum);
SHAPE(PesQuadratumLongqueue);
SHAPE(PesQuadratumOpenqueue);
SHAPE(PesQuassus);
SHAPE(PesQuassusInusitatus);
SHAPE(PesQuassusInusitatusLongqueue);
SHAPE(PesQuassusInusitatusOpenqueue);
SHAPE(PesQuassusLongqueue);
SHAPE(PesQuassusOpenqueue);
SHAPE(Porrectus);
SHAPE(PorrectusFlexus);
SHAPE(PorrectusFlexusLongqueue);
SHAPE(PorrectusFlexusNobar);
SHAPE(PorrectusLongqueue);
SHAPE(PorrectusNobar);
SHAPE(Punctum);
SHAPE(PunctumAscendens);
SHAPE(PunctumDeminutus);
SHAPE(PunctumDescendens);
SHAPE(PunctumInclinatumAuctus);
SHAPE(PunctumInclinatumDeminutus);
SHAPE(PunctumLineBL);
SHAPE(PunctumLineTL);
SHAPE(Quilisma);
SHAPE(QuilismaPes);
SHAPE(QuilismaPesQuadratum);
SHAPE(QuilismaPesQuadratumLongqueue);
SHAPE(QuilismaPesQuadratumOpenqueue);
SHAPE(StansPunctumInclinatum);
SHAPE(Salicus);
SHAPE(SalicusFlexus);
SHAPE(SalicusLongqueue);
SHAPE(Scandicus);
SHAPE(Sharp);
SHAPE(SharpParen);
SHAPE(Stropha);
SHAPE(StrophaAucta);
SHAPE(StrophaAuctaLongtail);
SHAPE(Torculus);
SHAPE(TorculusLiquescens);
SHAPE(TorculusLiquescensQuilisma);
SHAPE(TorculusQuilisma);
SHAPE(TorculusResupinus);
SHAPE(TorculusResupinusQuilisma);
SHAPE(Virga);
SHAPE(VirgaLongqueue);
SHAPE(VirgaOpenqueue);
SHAPE(VirgaReversa);
SHAPE(VirgaReversaAscendens);
SHAPE(VirgaReversaDescendens);
SHAPE(VirgaReversaLongqueue);
SHAPE(VirgaReversaLongqueueAscendens);
SHAPE(VirgaReversaLongqueueDescendens);
SHAPE(VirgaReversaOpenqueue);
SHAPE(VirgaReversaOpenqueueAscendens);
SHAPE(VirgaReversaOpenqueueDescendens);

#define LIQ(NAME) static const char *const LIQ_##NAME = #NAME
LIQ(Deminutus);
LIQ(Ascendens);
LIQ(Descendens);
LIQ(InitioDebilis);
LIQ(InitioDebilisDeminutus);
LIQ(InitioDebilisAscendens);
LIQ(InitioDebilisDescendens);
LIQ(Nothing);

#define FUSE(NAME) static const char *const FUSE_##NAME = #NAME
FUSE(Lower);
FUSE(LowerOblatus);
FUSE(Upper);
FUSE(UpperOblatus);
FUSE(Down);
FUSE(Up);

/* the value indicating to GregorioTeX that there is no flat */
#define NO_KEY_FLAT LOWEST_PITCH

static __inline signed char pitch_value(const signed char height) {
    /* right now height == pitch, but this function allows us to change
     * the offset easily */
    return height;
}

static __inline int bool_to_int(bool value) {
    return value? 1 : 0;
}

typedef enum queuetype {
    Q_ON_SPACE_BELOW_BOTTOM_LINE,
    Q_ON_SPACE_ABOVE_BOTTOM_LINE,
    Q_ON_BOTTOM_LINE,
    Q_ON_LINE_ABOVE_BOTTOM_LINE
} queuetype;

static queuetype adjusted_queuetype_of(const gregorio_note *const note,
        const gregorio_note *const queue_note, const signed char adjustment)
{
    switch (note->u.note.pitch + adjustment - LOWEST_PITCH) {
    case 0:
        return Q_ON_SPACE_BELOW_BOTTOM_LINE;
    case 1:
        return Q_ON_BOTTOM_LINE;
    case 2:
        return queue_note->low_ledger_line?
                Q_ON_SPACE_ABOVE_BOTTOM_LINE : Q_ON_SPACE_BELOW_BOTTOM_LINE;
    case 3:
        return queue_note->low_ledger_line?
                Q_ON_LINE_ABOVE_BOTTOM_LINE : Q_ON_BOTTOM_LINE;
    case 5:
    case 7:
    case 9:
    case 11:
    case 13:
        return Q_ON_LINE_ABOVE_BOTTOM_LINE;
    default:
        return Q_ON_SPACE_ABOVE_BOTTOM_LINE;
    }
}

static queuetype queuetype_of(const gregorio_note *const note) {
    return adjusted_queuetype_of(note, note, 0);
}

static grestyle_style gregoriotex_ignore_style = ST_NO_STYLE;
static grestyle_style gregoriotex_next_ignore_style = ST_NO_STYLE;

/*
 * The different liquescentiae are:
 * 'Nothing'
 * 'InitioDebilis'
 * 'Deminutus
 * 'Ascendens'
 * 'Descendens'
 * 'InitioDebilisDeminutus'
 * 'InitioDebilisAscendens'
 * 'InitioDebilisDescendens'
 *
 * They also are and must be the same as in squarize.py.
 */

static const char *gregoriotex_determine_liquescentia(
        gtex_glyph_liquescentia type, const gregorio_glyph *const glyph)
{
    gregorio_liquescentia liquescentia = glyph->u.notes.liquescentia;

    switch (type) {
    case LG_ALL:
        break;
    case LG_NO_INITIO:
        liquescentia &= ~L_INITIO_DEBILIS;
        break;
    case LG_ONLY_DEMINUTUS:
        liquescentia &= L_INITIO_DEBILIS | L_DEMINUTUS;
        break;
    case LG_FUSIBLE_INITIO:
        if (glyph->u.notes.fuse_to_next_glyph) {
            liquescentia &= L_INITIO_DEBILIS;
            break;
        }
        /* fall through */
    case LG_NONE:
        liquescentia = L_NO_LIQUESCENTIA;
        break;
    }

    /* now we convert liquescentia into the good GregorioTeX liquescentia
     * numbers */

    switch (liquescentia & ~L_FUSED) {
    case L_DEMINUTUS:
        return LIQ_Deminutus;
    case L_AUCTUS_ASCENDENS:
        return LIQ_Ascendens;
    case L_AUCTUS_DESCENDENS:
        return LIQ_Descendens;
    case L_INITIO_DEBILIS:
        return LIQ_InitioDebilis;
    case L_DEMINUTUS_INITIO_DEBILIS:
        return LIQ_InitioDebilisDeminutus;
    case L_AUCTUS_ASCENDENS_INITIO_DEBILIS:
        return LIQ_InitioDebilisAscendens;
    case L_AUCTUS_DESCENDENS_INITIO_DEBILIS:
        return LIQ_InitioDebilisDescendens;
    case L_NO_LIQUESCENTIA:
        /* break out and return "Nothing" */
        break;
    }

    return LIQ_Nothing;
}

static __inline int compute_ambitus(const gregorio_note *const current_note)
{
    int first = current_note->u.note.pitch;
    int second = current_note->next->u.note.pitch;
    int ambitus;
    if (first < second) {
        ambitus = second - first;
    } else {
        ambitus = first - second;
    }
    gregorio_assert2(ambitus >= 1 && ambitus <= MAX_AMBITUS, compute_ambitus,
            "unsupported ambitus: %d", ambitus, return 0);
    return ambitus;
}

static const char *compute_glyph_name(const gregorio_glyph *const glyph,
        const char *shape, const gtex_glyph_liquescentia ltype,
        bool is_single_note)
{
    static char buf[BUFSIZE];

    const char *liquescentia = gregoriotex_determine_liquescentia(ltype, glyph);
    const gregorio_note *current_note;
    int ambitus1, ambitus2, ambitus3, fuse_ambitus = 0;
    const char *fuse_head = "", *fuse_tail = "";
    const gregorio_glyph *previous = gregorio_previous_non_texverb_glyph(glyph);
    int fuse_to_next_note, fuse_from_previous_note =
            (previous && previous->type == GRE_GLYPH)
            ? previous->u.notes.fuse_to_next_glyph : 0;

    /* then we start making our formula */
    gregorio_assert(glyph, compute_glyph_name, "called with NULL pointer",
            return "");
    gregorio_assert(glyph->u.notes.first_note, compute_glyph_name,
            "called with a glyph that have no note", return "");

    fuse_to_next_note = glyph->u.notes.fuse_to_next_glyph;

    switch (glyph->u.notes.glyph_type) {
    case G_PODATUS:
    case G_PUNCTUM:
    case G_FLEXA:
        /* directionally head-fusible */
        if (fuse_from_previous_note < 0) {
            if (glyph->u.notes.first_note->u.note.shape != S_QUILISMA
                && glyph->u.notes.first_note->u.note.shape
                != S_QUILISMA_QUADRATUM) {
                if (fuse_from_previous_note < -1) {
                    fuse_head = FUSE_Lower;
                } else if (glyph->u.notes.first_note->u.note.shape
                        == S_ORISCUS_DESCENDENS
                        || glyph->u.notes.first_note->u.note.shape
                        == S_ORISCUS_SCAPUS_DESCENDENS) {
                    /* fuse_from_previous_note will be -1 here */
                    fuse_head = FUSE_LowerOblatus;
                }
            }
        } else if (fuse_from_previous_note > 0) {
            if (fuse_from_previous_note > 1) {
                fuse_head = FUSE_Upper;
            } else if (glyph->u.notes.first_note->u.note.shape
                    == S_ORISCUS_ASCENDENS
                    || glyph->u.notes.first_note->u.note.shape
                    == S_ORISCUS_SCAPUS_ASCENDENS) {
                /* fuse_from_previous_note will be 1 here */
                fuse_head = FUSE_UpperOblatus;
            }
        }
        break;

    default:
        /* not directionally head-fusible */
        break;
    }

    switch (glyph->u.notes.glyph_type) {
    case G_FLEXA:
        if (fuse_to_next_note <= 0) {
            /* a flexa is only fusible up */
            break;
        }
        /* else fall through */
    case G_VIRGA_REVERSA:
    case G_PUNCTUM:
        /* tail-fusible */
        if (fuse_to_next_note < 0) {
            fuse_tail = FUSE_Down;
            fuse_ambitus = -fuse_to_next_note;
        } else if (fuse_to_next_note > 0) {
            fuse_tail = FUSE_Up;
            fuse_ambitus = fuse_to_next_note;
        }

        if (*fuse_tail && liquescentia == LIQ_Nothing) {
            liquescentia = "";
        }
        break;

    default:
        /* not tail-fusible */
        break;
    }

    if (is_fused(glyph->u.notes.liquescentia)) {
        if (shape == SHAPE_AscendensOriscusScapus
                || shape == SHAPE_AscendensOriscusScapusLongqueue
                || shape == SHAPE_AscendensOriscusScapusOpenqueue) {
            shape = SHAPE_AscendensOriscus;
        } else if (shape == SHAPE_DescendensOriscusScapus
                || shape == SHAPE_DescendensOriscusScapusLongqueue
                || shape == SHAPE_DescendensOriscusScapusOpenqueue) {
            shape = SHAPE_DescendensOriscus;
        } else if (shape == SHAPE_FlexusOriscusScapus
                || shape == SHAPE_FlexusOriscusScapusLongqueue
                || shape == SHAPE_FlexusOriscusScapusOpenqueue) {
            shape = SHAPE_FlexusOriscus;
        } else if (shape == SHAPE_FlexusOriscusScapusInusitatus
                || shape == SHAPE_FlexusOriscusScapusInusitatusLongqueue
                || shape == SHAPE_FlexusOriscusScapusInusitatusOpenqueue) {
            shape = SHAPE_FlexusOriscusInusitatus;
        }
    }

    current_note = glyph->u.notes.first_note;
    if (is_single_note) {
        if (liquescentia == LIQ_Nothing) {
            liquescentia = "";
        }
        if (!(*fuse_tail) && fuse_head != FUSE_UpperOblatus
                && fuse_head != FUSE_LowerOblatus) {
            /* single note fused shapes have weird names */
            if (fuse_head == FUSE_Upper) {
                if (shape == SHAPE_Punctum) {
                    shape = SHAPE_PunctumLineBL;
                } else if (shape == SHAPE_AscendensOriscus) {
                    shape = SHAPE_AscendensOriscusLineBL;
                } else if (shape == SHAPE_DescendensOriscus) {
                    shape = SHAPE_DescendensOriscusLineBL;
                }
            } else if (fuse_head == FUSE_Lower) {
                if (shape == SHAPE_Punctum) {
                    shape = SHAPE_PunctumLineTL;
                } else if (shape == SHAPE_AscendensOriscus) {
                    shape = SHAPE_AscendensOriscusLineTL;
                } else if (shape == SHAPE_DescendensOriscus) {
                    shape = SHAPE_DescendensOriscusLineTL;
                }
            }
            fuse_head = "";
        }
        gregorio_snprintf(buf, BUFSIZE, "%s%s%s%s%s", fuse_head, shape,
                tex_ambitus[fuse_ambitus], liquescentia, fuse_tail);
        return buf;
    }
    gregorio_assert(current_note->next, compute_glyph_name,
            "called with a multi-note glyph that has only one note", return "");
    gregorio_assert((ambitus1 = compute_ambitus(current_note)),
            compute_glyph_name, "unexpected unison on multi-note glyph",
            return "");
    if (is_fused(glyph->u.notes.liquescentia)) {
        if (shape == SHAPE_Flexus || shape == SHAPE_FlexusLongqueue
                || shape == SHAPE_FlexusOpenqueue) {
            if (fuse_to_next_note) {
                fuse_head = "";
            }
            if (*fuse_head) {
                shape = SHAPE_Flexus;
            } else {
                shape = SHAPE_FlexusNobar;
            }
        } else if (shape == SHAPE_Porrectus
                || shape == SHAPE_PorrectusLongqueue) {
            shape = SHAPE_PorrectusNobar;
        }
    } else {
        if (fuse_to_next_note && (shape == SHAPE_FlexusLongqueue
                    || shape == SHAPE_FlexusOpenqueue)) {
            /* a porrectus-like flexus has no longqueue variant */
            shape = SHAPE_Flexus;
        }
    }
    if (shape == SHAPE_SalicusLongqueue && liquescentia != LIQ_Nothing) {
        /* the salicus queue is at the end of the glyph, and it doesn't exist
         * for the liquescent forms */
        shape = SHAPE_Salicus;
    }
    current_note = current_note->next;
    if (!current_note->next) {
        gregorio_snprintf(buf, BUFSIZE, "%s%s%s%s%s%s", fuse_head, shape,
                tex_ambitus[ambitus1], tex_ambitus[fuse_ambitus],
                liquescentia, fuse_tail);
        return buf;
    }
    gregorio_assert((ambitus2 = compute_ambitus(current_note)),
            compute_glyph_name, "unexpected unison on multi-note glyph",
            return "");
    current_note = current_note->next;
    if (!current_note->next) {
        gregorio_snprintf(buf, BUFSIZE, "%s%s%s%s%s%s%s", fuse_head, shape,
                tex_ambitus[ambitus1], tex_ambitus[ambitus2],
                tex_ambitus[fuse_ambitus], liquescentia, fuse_tail);
        return buf;
    }
    gregorio_assert((ambitus3 = compute_ambitus(current_note)),
            compute_glyph_name, "unexpected unison on multi-note glyph",
            return "");
    gregorio_snprintf(buf, BUFSIZE, "%s%s%s%s%s%s%s%s", fuse_head, shape,
            tex_ambitus[ambitus1], tex_ambitus[ambitus2], tex_ambitus[ambitus3],
            tex_ambitus[fuse_ambitus], liquescentia, fuse_tail);
    return buf;
}

static const char *fusible_queued_shape(const gregorio_note *const note,
        const gregorio_glyph *const glyph,
        const char *const base_shape, const char *const longqueue_shape,
        const char *const openqueue_shape)
{
    const char *name = NULL;
    if (glyph->u.notes.fuse_to_next_glyph < 0) {
        /* queue size depends on the following note if fused down */
        bool ambitus_one = (glyph->u.notes.fuse_to_next_glyph == -1);
        switch (adjusted_queuetype_of(note, note,
                    glyph->u.notes.fuse_to_next_glyph)) {
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
            if (ambitus_one) {
                name = openqueue_shape;
                break;
            }
            /* else fall through */
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
            /* at ambitus one, long and short are swapped becuase the queue where
             * the second note is on a space is longer than on a line */
            name = ambitus_one? longqueue_shape : base_shape;
            break;
        case Q_ON_BOTTOM_LINE:
            if (ambitus_one) {
                name = openqueue_shape;
                break;
            }
            /* else fall through */
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            /* at ambitus one, long and short are swapped becuase the queue where
             * the second note is on a line is shorter than on a space */
            name = ambitus_one? base_shape : longqueue_shape;
            break;
        }
    } else if (glyph->u.notes.fuse_to_next_glyph) {
        /* TODO (5.0?) handle queue size on upwards fusion */
        switch (queuetype_of(note)) {
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
        case Q_ON_BOTTOM_LINE:
            name = base_shape;
            break;
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            name = longqueue_shape;
            break;
        }
    } else {
        switch (queuetype_of(note)) {
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
            name = base_shape;
            break;
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        case Q_ON_BOTTOM_LINE:
            name = openqueue_shape;
            break;
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            name = longqueue_shape;
            break;
        }
    }
    gregorio_not_null(name, fusible_queued_shape, return base_shape);
    return compute_glyph_name(glyph, name, LG_NONE, true);
}

static __inline char *code_point(const char *const shape, const bool is_cavum,
        char *const buf, const size_t bufsize)
{
    if (is_cavum) {
        gregorio_snprintf(buf, bufsize, "\\GreCavum{%s}", shape);
    } else {
        gregorio_snprintf(buf, bufsize, "\\GreCP%s", shape);
    }
    return buf;
}

static const char *determine_note_glyph_name(const gregorio_note *const note,
        const gregorio_glyph *glyph, gtex_alignment *type)
{
    static char buf[128], cpbuf[96];
    const char *name = "";

    gregorio_assert(note, determine_note_glyph_name, "called with NULL pointer",
            return "");

    *type = AT_ONE_NOTE;
    switch (note->u.note.shape) {
    case S_PUNCTUM_INCLINATUM_ASCENDENS:
        *type = AT_PUNCTUM_INCLINATUM;
        return SHAPE_AscendensPunctumInclinatum;
    case S_PUNCTUM_INCLINATUM_STANS:
        *type = AT_PUNCTUM_INCLINATUM;
        return SHAPE_StansPunctumInclinatum;
    case S_PUNCTUM_INCLINATUM_DESCENDENS:
        *type = AT_PUNCTUM_INCLINATUM;
        return SHAPE_DescendensPunctumInclinatum;
    case S_PUNCTUM_INCLINATUM_DEMINUTUS:
        return SHAPE_PunctumInclinatumDeminutus;
    case S_PUNCTUM_INCLINATUM_AUCTUS:
        return SHAPE_PunctumInclinatumAuctus;
    case S_PUNCTUM:
        return compute_glyph_name(glyph, SHAPE_Punctum, LG_FUSIBLE_INITIO, true);
    case S_PUNCTUM_AUCTUS_ASCENDENS:
        return SHAPE_PunctumAscendens;
    case S_PUNCTUM_AUCTUS_DESCENDENS:
        return SHAPE_PunctumDescendens;
    case S_PUNCTUM_DEMINUTUS:
        return SHAPE_PunctumDeminutus;
    case S_LINEA:
        return SHAPE_Linea;
    case S_LINEA_PUNCTUM:
        return SHAPE_LineaPunctum;
    case S_VIRGA:
        switch (queuetype_of(note)) {
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
            return SHAPE_Virga;
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        case Q_ON_BOTTOM_LINE:
            return SHAPE_VirgaOpenqueue;
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            return SHAPE_VirgaLongqueue;
        } /* all cases return, so this line is not hit; LCOV_EXCL_LINE */
        /* LCOV_EXCL_START */
        gregorio_fail2(determine_note_glyph_name, "unknown queuetype: %d",
                queuetype_of(note));
        return "";
        /* LCOV_EXCL_STOP */
    case S_VIRGA_REVERSA:
        switch (note->u.note.liquescentia) {
        case L_AUCTUS_ASCENDENS:
            switch (queuetype_of(note)) {
            case Q_ON_SPACE_BELOW_BOTTOM_LINE:
            case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
                name = SHAPE_VirgaReversaAscendens;
                break;
            case Q_ON_BOTTOM_LINE:
                name = SHAPE_VirgaReversaOpenqueueAscendens;
                break;
            case Q_ON_LINE_ABOVE_BOTTOM_LINE:
                name = SHAPE_VirgaReversaLongqueueAscendens;
                break;
            }
            if (note->u.note.pitch - LOWEST_PITCH == 3) {
                /* if we're on the 'd' line, the queue could be long or short */
                gregorio_snprintf(buf, sizeof buf,
                        "VirgaReversaAscendensOnDLine{%s}", code_point(name,
                            glyph->u.notes.is_cavum, cpbuf, sizeof cpbuf));
                return buf;
            }
            return name;
        case L_AUCTUS_DESCENDENS:
            switch (queuetype_of(note)) {
            case Q_ON_SPACE_BELOW_BOTTOM_LINE:
            case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
                return SHAPE_VirgaReversaDescendens;
            case Q_ON_BOTTOM_LINE:
                return SHAPE_VirgaReversaOpenqueueDescendens;
            case Q_ON_LINE_ABOVE_BOTTOM_LINE:
                return SHAPE_VirgaReversaLongqueueDescendens;
            } /* all cases return, so this line is not hit; LCOV_EXCL_LINE */
            /* LCOV_EXCL_START */
            gregorio_fail2(determine_note_glyph_name, "unknown queuetype: %d",
                    queuetype_of(note));
            return "";
            /* LCOV_EXCL_STOP */
            default:
                return fusible_queued_shape(note, glyph, SHAPE_VirgaReversa,
                        SHAPE_VirgaReversaLongqueue, SHAPE_VirgaReversaOpenqueue);
            }
    case S_ORISCUS_ASCENDENS:
        *type = AT_ORISCUS;
        return compute_glyph_name(glyph, SHAPE_AscendensOriscus, LG_NONE, true);
    case S_ORISCUS_DESCENDENS:
        *type = AT_ORISCUS;
        return compute_glyph_name(glyph, SHAPE_DescendensOriscus, LG_NONE, true);
    case S_ORISCUS_DEMINUTUS:
        *type = AT_ORISCUS;
        return SHAPE_OriscusDeminutus;
    case S_QUILISMA:
        *type = AT_QUILISMA;
        return compute_glyph_name(glyph, SHAPE_Quilisma, LG_NONE, true);
    case S_ORISCUS_SCAPUS_ASCENDENS:
        return fusible_queued_shape(note, glyph, SHAPE_AscendensOriscusScapus,
                SHAPE_AscendensOriscusScapusLongqueue,
                SHAPE_AscendensOriscusScapusOpenqueue);
    case S_ORISCUS_SCAPUS_DESCENDENS:
        return fusible_queued_shape(note, glyph, SHAPE_DescendensOriscusScapus,
                SHAPE_DescendensOriscusScapusLongqueue,
                SHAPE_DescendensOriscusScapusOpenqueue);
    case S_STROPHA:
        *type = AT_STROPHA;
        if (!(note->u.note.liquescentia &
                (L_AUCTUS_ASCENDENS | L_AUCTUS_DESCENDENS))) {
            return SHAPE_Stropha;
        }
        /* fall through */
    case S_STROPHA_AUCTA:
        *type = AT_STROPHA;
        switch (queuetype_of(note)) {
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
            return SHAPE_StrophaAucta;
        case Q_ON_BOTTOM_LINE:
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            return SHAPE_StrophaAuctaLongtail;
        } /* all cases return, so this line is not hit; LCOV_EXCL_LINE */
        /* LCOV_EXCL_START */
        gregorio_fail2(determine_note_glyph_name, "unknown queuetype: %d",
                queuetype_of(note));
        return "";
        /* LCOV_EXCL_STOP */
    case S_FLAT:
        return SHAPE_Flat;
    case S_FLAT_PAREN:
        return SHAPE_FlatParen;
    case S_SHARP:
        return SHAPE_Sharp;
    case S_SHARP_PAREN:
        return SHAPE_SharpParen;
    case S_NATURAL:
        return SHAPE_Natural;
    case S_NATURAL_PAREN:
        return SHAPE_NaturalParen;
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail2(determine_note_glyph_name,
                "called with unknown shape: %s",
                gregorio_shape_to_string(note->u.note.shape));
        return "";
        /* LCOV_EXCL_STOP */
    }
}

static __inline gregorio_note *first_note_of(
        const gregorio_glyph *const glyph) {
    assert(glyph->type == GRE_GLYPH);
    assert(glyph->u.notes.first_note);
    assert(glyph->u.notes.first_note->type == GRE_NOTE);
    return glyph->u.notes.first_note;
}

static __inline signed char first_pitch_of(const gregorio_glyph *const glyph) {
    return first_note_of(glyph)->u.note.pitch;
}

static __inline gregorio_note *second_note_of(
        const gregorio_glyph *const glyph) {
    assert(glyph->type == GRE_GLYPH);
    assert(glyph->u.notes.first_note);
    assert(glyph->u.notes.first_note->type == GRE_NOTE);
    assert(glyph->u.notes.first_note->next);
    assert(glyph->u.notes.first_note->next->type == GRE_NOTE);
    return glyph->u.notes.first_note->next;
}

static __inline signed char second_pitch_of(const gregorio_glyph *const glyph) {
    return second_note_of(glyph)->u.note.pitch;
}

static __inline gregorio_note *third_note_of(
        const gregorio_glyph *const glyph) {
    assert(glyph->type == GRE_GLYPH);
    assert(glyph->u.notes.first_note);
    assert(glyph->u.notes.first_note->type == GRE_NOTE);
    assert(glyph->u.notes.first_note->next);
    assert(glyph->u.notes.first_note->next->type == GRE_NOTE);
    assert(glyph->u.notes.first_note->next->next);
    assert(glyph->u.notes.first_note->next->next->type == GRE_NOTE);
    return glyph->u.notes.first_note->next->next;
}

static __inline signed char third_pitch_of(const gregorio_glyph *const glyph) {
    return third_note_of(glyph)->u.note.pitch;
}

static __inline const char *porrectus_shape(const gregorio_glyph *const glyph,
        const char *base_shape, const char *longqueue_shape) {
    const gregorio_note *const first_note = first_note_of(glyph);
    if ((glyph->u.notes.glyph_type == G_PORRECTUS
                && (glyph->u.notes.liquescentia & L_DEMINUTUS))
            || first_note->u.note.pitch - second_pitch_of(glyph) == 1) {
        switch (queuetype_of(first_note)) {
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
        case Q_ON_BOTTOM_LINE:
            return base_shape;
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            return longqueue_shape;
        }
    } /* must be optimized out; LCOV_EXCL_LINE */
    return base_shape;
}

static __inline const char *flexus_shape(const gregorio_glyph *const glyph,
        const signed char ambitus, const char *base_shape,
        const char *longqueue_shape, const char *openqueue_shape) {
    const bool ambitus_one = (ambitus == 1);
    switch (adjusted_queuetype_of(second_note_of(glyph), first_note_of(glyph),
                0)) {
    case Q_ON_SPACE_BELOW_BOTTOM_LINE:
        if (ambitus_one) {
            return openqueue_shape;
        }
        /* else fall through */
    case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
        /* at ambitus one, long and short are swapped becuase the queue where
         * the second note is on a space is longer than on a line */
        return ambitus_one? longqueue_shape : base_shape;
    case Q_ON_BOTTOM_LINE:
        if (ambitus_one) {
            return openqueue_shape;
        }
        /* else fall through */
    case Q_ON_LINE_ABOVE_BOTTOM_LINE:
        /* at ambitus one, long and short are swapped becuase the queue where
         * the second note is on a line is shorter than on a space */
        return ambitus_one? base_shape : longqueue_shape;
    }
    /* not reachable unless there's a programming error */
    /* LCOV_EXCL_START */
    gregorio_fail(flexus_shape, "unexpected queue length");
    return base_shape;
    /* LCOV_EXCL_STOP */
}

static __inline const char *quadratum_shape(const gregorio_glyph *const glyph,
        const char *base_shape, const char *longqueue_shape,
        const char *openqueue_shape) {
    const bool ambitus_one =
            (second_pitch_of(glyph) - first_pitch_of(glyph) == 1);
    if (!is_tail_liquescentia(glyph->u.notes.liquescentia)) {
        switch (adjusted_queuetype_of(first_note_of(glyph),
                    second_note_of(glyph), 0)) {
        case Q_ON_SPACE_BELOW_BOTTOM_LINE:
            if (ambitus_one) {
                return openqueue_shape;
            }
            /* else fall through */
        case Q_ON_SPACE_ABOVE_BOTTOM_LINE:
            /* at ambitus one, long and short are swapped becuase the queue
             * where the first note is on a space is longer than on a line */
            return ambitus_one? longqueue_shape : base_shape;
        case Q_ON_BOTTOM_LINE:
            if (ambitus_one) {
                return openqueue_shape;
            }
            /* else fall through */
        case Q_ON_LINE_ABOVE_BOTTOM_LINE:
            /* at ambitus one, long and short are swapped becuase the queue
             * where the first note is on a line is shorter than on a space */
            return ambitus_one? base_shape : longqueue_shape;
        }
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail(quadratum_shape, "unexpected queue length");
        /* fall out of the conditional */
    }
    /* LCOV_EXCL_STOP */
    return base_shape;
}

/* the function that calculates the number of the glyph. It also
 * calculates the type, used for determining the position of signs. Type is
 * very basic, it is only the global dimensions : torculus, one_note, etc. */

const char *gregoriotex_determine_glyph_name(const gregorio_glyph *const glyph,
        gtex_alignment *const type, gtex_type *const gtype)
{
    const char *shape = NULL;
    gtex_glyph_liquescentia ltype;
    signed char ambitus;
    const gregorio_note *second_note;
    gregorio_assert(glyph, gregoriotex_determine_glyph_name,
            "called with NULL pointer", return "");
    gregorio_assert(glyph->u.notes.first_note, gregoriotex_determine_glyph_name,
            "called with a glyph that has no note", return "");
    *gtype = T_ONE_NOTE;
    switch (glyph->u.notes.glyph_type) {
    case G_PODATUS:
        switch (glyph->u.notes.first_note->u.note.shape) {
        case S_QUILISMA:
            *type = AT_QUILISMA;
            /* the next if is because we made the choice that AUCTUS shapes
             * look like pes quadratum. */
            if (glyph->u.notes.liquescentia
                    & (L_AUCTUS_ASCENDENS | L_AUCTUS_DESCENDENS)) {
                *gtype = T_QUILISMA_PES_QUADRATUM;
                shape = SHAPE_QuilismaPesQuadratum;
            } else {
                *gtype = T_QUILISMA_PES;
                shape = SHAPE_QuilismaPes;
            }
            ltype = LG_NO_INITIO;
            break;
        case S_ORISCUS_ASCENDENS:
        case S_ORISCUS_SCAPUS_ASCENDENS:
            *type = AT_ORISCUS;
            *gtype = T_PES_QUASSUS;
            shape = quadratum_shape(glyph, SHAPE_PesQuassus,
                    SHAPE_PesQuassusLongqueue, SHAPE_PesQuassusOpenqueue);
            ltype = LG_NO_INITIO;
            break;
        case S_ORISCUS_DESCENDENS:
        case S_ORISCUS_SCAPUS_DESCENDENS:
            *type = AT_ORISCUS;
            *gtype = T_PES_QUASSUS;
            shape = quadratum_shape(glyph, SHAPE_PesQuassusInusitatus,
                    SHAPE_PesQuassusInusitatusLongqueue,
                    SHAPE_PesQuassusInusitatusOpenqueue);
            ltype = LG_NO_INITIO;
            break;
        default:
            *type = AT_ONE_NOTE;
            if (glyph->u.notes.liquescentia
                    & (L_AUCTUS_ASCENDENS | L_AUCTUS_DESCENDENS)) {
                *gtype = T_PES_QUADRATUM;
                shape = SHAPE_PesQuadratum;
            } else {
                *gtype = T_PES;
                shape = SHAPE_Pes;
            }
            ltype = LG_ALL;
            break;
        }
        break;
    case G_PES_QUADRATUM:
        switch (glyph->u.notes.first_note->u.note.shape) {
        case S_QUILISMA:
            *type = AT_QUILISMA;
            *gtype = T_QUILISMA_PES_QUADRATUM;
            shape = quadratum_shape(glyph, SHAPE_QuilismaPesQuadratum,
                   SHAPE_QuilismaPesQuadratumLongqueue,
                   SHAPE_QuilismaPesQuadratumOpenqueue);
            ltype = LG_NO_INITIO;
            break;
        default:
            *type = AT_ONE_NOTE;
            *gtype = T_PES_QUADRATUM;
            shape = quadratum_shape(glyph, SHAPE_PesQuadratum,
                   SHAPE_PesQuadratumLongqueue, SHAPE_PesQuadratumOpenqueue);
            ltype = LG_ALL;
            break;
        }
        break;
    case G_PES_ASCENDENS_ORISCUS:
        *type = AT_ONE_NOTE;
        *gtype = T_PES_ORISCUS;
        shape = SHAPE_PesAscendensOriscus;
        ltype = LG_ALL;
        break;
    case G_PES_DESCENDENS_ORISCUS:
        *type = AT_ONE_NOTE;
        *gtype = T_PES_ORISCUS;
        shape = SHAPE_PesDescendensOriscus;
        ltype = LG_ALL;
        break;
    case G_FLEXA:
        ambitus = first_pitch_of(glyph) - second_pitch_of(glyph);
        if (glyph->u.notes.liquescentia & L_DEMINUTUS) {
            *type = AT_FLEXUS_DEMINUTUS;
        } else {
            if (ambitus == 1) {
                *type = AT_FLEXUS_1;
            } else {
                *type = AT_FLEXUS;
            }
        }
        switch (glyph->u.notes.first_note->u.note.shape) {
        case S_ORISCUS_ASCENDENS:
            *gtype = T_FLEXUS_ORISCUS;
            shape = SHAPE_FlexusOriscusInusitatus;
            ltype = LG_NO_INITIO;
            break;

        case S_ORISCUS_DESCENDENS:
            *gtype = T_FLEXUS_ORISCUS;
            shape = SHAPE_FlexusOriscus;
            ltype = LG_NO_INITIO;
            break;

        case S_ORISCUS_SCAPUS_ASCENDENS:
            *gtype = T_FLEXUS_ORISCUS_SCAPUS;
            shape = flexus_shape(glyph, ambitus,
                    SHAPE_FlexusOriscusScapusInusitatus,
                    SHAPE_FlexusOriscusScapusInusitatusLongqueue,
                    SHAPE_FlexusOriscusScapusInusitatusOpenqueue);
            ltype = LG_NO_INITIO;
            break;

        case S_ORISCUS_SCAPUS_DESCENDENS:
            *gtype = T_FLEXUS_ORISCUS_SCAPUS;
            shape = flexus_shape(glyph, ambitus, SHAPE_FlexusOriscusScapus,
                    SHAPE_FlexusOriscusScapusLongqueue,
                    SHAPE_FlexusOriscusScapusOpenqueue);
            ltype = LG_NO_INITIO;
            break;

        default:
            *gtype = glyph->u.notes.fuse_to_next_glyph? T_PORRECTUS : T_FLEXUS;
            shape = flexus_shape(glyph, ambitus, SHAPE_Flexus,
                    SHAPE_FlexusLongqueue, SHAPE_FlexusOpenqueue);
            ltype = LG_NO_INITIO;
            break;
        }
        break;
    case G_TORCULUS:
        *gtype = T_TORCULUS;
        if (glyph->u.notes.first_note->u.note.shape == S_QUILISMA) {
            *type = AT_QUILISMA;
            shape = SHAPE_TorculusQuilisma;
            ltype = LG_NO_INITIO;
        } else {
            *type = AT_ONE_NOTE;
            shape = SHAPE_Torculus;
            ltype = LG_ALL;
        }
        break;
    case G_TORCULUS_LIQUESCENS:
        *gtype = T_TORCULUS_LIQUESCENS;
        if (glyph->u.notes.first_note->u.note.shape == S_QUILISMA) {
            *type = AT_QUILISMA;
            shape = SHAPE_TorculusLiquescensQuilisma;
        } else {
            *type = AT_ONE_NOTE;
            shape = SHAPE_TorculusLiquescens;
        }
        ltype = LG_ONLY_DEMINUTUS;
        break;
    case G_TORCULUS_RESUPINUS_FLEXUS:
        *type = AT_ONE_NOTE;
        *gtype = T_TORCULUS_RESUPINUS_FLEXUS;
        break;
    case G_PORRECTUS:
        *type = AT_PORRECTUS;
        *gtype = T_PORRECTUS;
        shape = porrectus_shape(glyph, SHAPE_Porrectus,
                SHAPE_PorrectusLongqueue);
        ltype = LG_NO_INITIO;
        break;
    case G_TORCULUS_RESUPINUS:
        *gtype = T_TORCULUS_RESUPINUS;
        if (glyph->u.notes.first_note->u.note.shape == S_QUILISMA) {
            *type = AT_QUILISMA;
            shape = SHAPE_TorculusResupinusQuilisma;
        } else {
            *type = AT_ONE_NOTE;
            shape = SHAPE_TorculusResupinus;
        }
        ltype = LG_ALL;
        break;
    case G_PORRECTUS_FLEXUS:
        *type = AT_PORRECTUS;
        *gtype = T_PORRECTUS_FLEXUS;
        shape = porrectus_shape(glyph, SHAPE_PorrectusFlexus,
                SHAPE_PorrectusFlexusLongqueue);
        ltype = LG_NO_INITIO;
        break;
    case G_PORRECTUS_NO_BAR:
        *type = AT_PORRECTUS;
        *gtype = T_TORCULUS_RESUPINUS;
        shape = SHAPE_PorrectusNobar;
        ltype = LG_NO_INITIO;
        break;
    case G_PORRECTUS_FLEXUS_NO_BAR:
        *type = AT_PORRECTUS;
        *gtype = T_TORCULUS_RESUPINUS_FLEXUS;
        shape = SHAPE_PorrectusFlexusNobar;
        ltype = LG_NO_INITIO;
        break;
    case G_ANCUS:
        *type = AT_ONE_NOTE;
        gregorio_assert(glyph->u.notes.liquescentia & L_DEMINUTUS,
                    gregoriotex_determine_glyph_name,
                    "encountered non-deminutus ancus", break);
        second_note = second_note_of(glyph);
        if (first_pitch_of(glyph) - second_note->u.note.pitch == 1) {
            *type = AT_FLEXUS_1;
        } else {
            *type = AT_FLEXUS;
        }
        *gtype = T_ANCUS;
        ambitus = first_pitch_of(glyph) - second_pitch_of(glyph);
        shape = flexus_shape(glyph, ambitus, SHAPE_Ancus,
                    SHAPE_AncusLongqueue, SHAPE_Ancus);
        ltype = LG_ONLY_DEMINUTUS;
        break;
    case G_SCANDICUS:
        *type = AT_ONE_NOTE;
        *gtype = T_SCANDICUS;
        shape = SHAPE_Scandicus;
        ltype = LG_NO_INITIO;
        break;
    case G_SALICUS:
        *type = AT_ONE_NOTE;
        *gtype = T_SALICUS;
        ambitus = third_pitch_of(glyph) - second_pitch_of(glyph);
        shape = flexus_shape(glyph, ambitus, SHAPE_Salicus,
                    SHAPE_SalicusLongqueue, SHAPE_Salicus);
        ltype = LG_NO_INITIO;
        break;
    case G_SALICUS_FLEXUS:
        *type = AT_ONE_NOTE;
        *gtype = T_SALICUS_FLEXUS;
        shape = SHAPE_SalicusFlexus;
        ltype = LG_NO_INITIO;
        break;
    case G_PUNCTUM_INCLINATUM:
    case G_PUNCTA_INCLINATA:
    case G_2_PUNCTA_INCLINATA_DESCENDENS:
    case G_3_PUNCTA_INCLINATA_DESCENDENS:
    case G_4_PUNCTA_INCLINATA_DESCENDENS:
    case G_5_PUNCTA_INCLINATA_DESCENDENS:
    case G_2_PUNCTA_INCLINATA_ASCENDENS:
    case G_3_PUNCTA_INCLINATA_ASCENDENS:
    case G_4_PUNCTA_INCLINATA_ASCENDENS:
    case G_5_PUNCTA_INCLINATA_ASCENDENS:
    case G_PUNCTUM:
    case G_STROPHA:
    case G_VIRGA:
    case G_VIRGA_REVERSA:
    case G_STROPHA_AUCTA:
    case G_DISTROPHA:
    case G_DISTROPHA_AUCTA:
    case G_TRISTROPHA:
    case G_TRISTROPHA_AUCTA:
    case G_BIVIRGA:
    case G_TRIVIRGA:
    case G_ALTERATION:
        *type = AT_ONE_NOTE;
        break;
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail2(gregoriotex_determine_glyph_name,
                "called with unknown glyph: %s",
                gregorio_glyph_type_to_string(glyph->u.notes.glyph_type));
        break;
        /* LCOV_EXCL_STOP */
    }
    if (shape) {
        shape = compute_glyph_name(glyph, shape, ltype, false);
    }
    /* we fix *type with initio_debilis */
    if (*type == AT_ONE_NOTE) {
        if (is_initio_debilis(glyph->u.notes.liquescentia)) {
            *type = AT_INITIO_DEBILIS;
        }
    }

    return shape;
}

/**
 * This now does nothing useful, but we keep it here in case it may
 * be needed in future.
 */
static void gregoriotex_write_voice_info(FILE *f, gregorio_voice_info *voice_info)
{
    gregorio_assert(f && voice_info, gregoriotex_write_voice_info,
            "file or voice_info passed as NULL", return);
}

/* this function indicates if the syllable is the last of the line or score. */
static bool is_last_of_line(gregorio_syllable *syllable)
{
    gregorio_element *current_element = NULL;
    if (!(syllable->next_syllable) || ((syllable->next_syllable->elements)[0]
                && (syllable->next_syllable->elements)[0]->type
                == GRE_END_OF_LINE)) {
        /* the next syllable start by an end of line */
        return true;
    }
    if (syllable->elements) {
        current_element = (syllable->elements)[0];
        while (current_element) {
            if (current_element->type == GRE_END_OF_LINE) {
                /* we return true only if the end of line is the last element */
                if (!(current_element->next)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                current_element = current_element->next;
            }
        }
    }
    return false;
}

/*
 * ! @brief Prints the beginning of each text style
 */
static void gtex_write_begin(FILE *f, grestyle_style style)
{
    if (style == gregoriotex_ignore_style) {
        return;
    }
    switch (style) {
    case ST_ITALIC:
        fprintf(f, "\\GreItalic{");
        break;
    case ST_SMALL_CAPS:
        fprintf(f, "\\GreSmallCaps{");
        break;
    case ST_BOLD:
        fprintf(f, "\\GreBold{");
        break;
    case ST_FORCED_CENTER:
    case ST_CENTER:
        fprintf(f, "}{");
        break;
    case ST_TT:
        fprintf(f, "\\GreTypewriter{");
        break;
    case ST_UNDERLINED:
        fprintf(f, "\\GreUnderline{");
        break;
    case ST_COLORED:
        fprintf(f, "\\GreColored{");
        break;
    case ST_ELISION:
        fprintf(f, "\\GreElision{");
        break;
    case ST_FIRST_WORD:
        fprintf(f, "\\GreFirstWord{");
        break;
    case ST_FIRST_SYLLABLE:
        fprintf(f, "\\GreFirstSyllable{");
        break;
    case ST_FIRST_SYLLABLE_INITIAL:
        fprintf(f, "\\GreFirstSyllableInitial{");
        break;
    case ST_PROTRUSION_FACTOR:
        fprintf(f, "\\GreProtrusion{");
        break;
    case ST_PROTRUSION:
        fprintf(f, "{");
        break;
    default:
        break;
    }
}

/**
 * @brief Ends each text style
 */
static void gtex_write_end(FILE *f, grestyle_style style)
{
    if (style == gregoriotex_ignore_style) {
        return;
    }
    switch (style) {
    case ST_FORCED_CENTER:
    case ST_CENTER:
    case ST_SYLLABLE_INITIAL:
        fprintf(f, "}{");
        break;
    case ST_INITIAL:
        break;
    default:
        fprintf(f, "}");
        break;
    }
}

static __inline void tex_escape_text(FILE *const f, const char *text)
{
    /* We escape these characters into \string\ddd (where ddd is the decimal
     * ASCII value of the character) for most escapes, and into \string\n for
     * newlines. We do it this way to get the "raw" string values through TeX
     * and into Lua, where the sequences become \ddd and \n respectively and
     * are translated into their byte values. Lua can then decide whether the
     * full strings should be evaluated by TeX as TeX or as strings */
    for (; *text; ++text) {
        switch (*text) {
        case '\\':
        case '{':
        case '}':
        case '~':
        case '%': /* currently, we'll never get %, but handle it anyway */
        case '#':
        case '"':
            /* these characters have special meaning to TeX */
            fprintf(f, "\\string\\%03d", *text);
            break;
        case '\n':
            fprintf(f, "\\string\\n");
            break;
        case '\r':
            /* ignore */
            break;
        default:
            /* UTF-8 multibyte sequences will fall into here, which is fine */
            fputc(*text, f);
            break;
        }
    }
}

static __inline void tex_escape_wtext(FILE *const f, const grewchar *text)
{
    /* We escape these characters into \string\ddd (where ddd is the decimal
     * ASCII value of the character) for most escapes, and into \string\n for
     * newlines. We do it this way to get the "raw" string values through TeX
     * and into Lua, where the sequences become \ddd and \n respectively and
     * are translated into their byte values. Lua can then decide whether the
     * full strings should be evaluated by TeX as TeX or as strings */
    for (; *text; ++text) {
        switch (*text) {
        case L'\\':
        case L'{':
        case L'}':
        case L'~':
        case L'%': /* currently, we'll never get %, but handle it anyway */
        case L'#':
        case L'"':
            /* these characters have special meaning to TeX */
            fprintf(f, "\\string\\%03d", *text);
            break;
        /* There is currently no way to get a carriage return or a newline into
         * an <sp>, but we'll leave this code here, but #if'd out, in case we
         * need this function in a different context */
#if 0
        case L'\n':
            fprintf(f, "\\string\\n");
            break;
        case L'\r':
            / * ignore * /
            break;
#endif
        default:
            gregorio_print_unichar(f, *text);
            break;
        }
    }
}

/*
 * ! @brief Writes GregorioTeX special characters. This function takes the
 * special characters as input (i.e. from gabc representation), and writes them
 * * in GregorioTeX form.
 */
static void gtex_write_special_char(FILE *f, const grewchar *special_char)
{
    fprintf(f, "\\GreSpecial{");
    tex_escape_wtext(f, special_char);
    fprintf(f, "}");
}

static void gtex_write_verb(FILE *f, const grewchar *first_char)
{
    gregorio_print_unistring(f, first_char);
}

static void gtex_print_char(FILE *f, const grewchar to_print)
{
    switch (to_print) {
    case L'*':
        fprintf(f, "\\GreStar{}");
        break;
    case L'%':
        /* there's currently no way to get a % into gabc, so this wont be hit,
         * but we leave it here for safety and possible future use */
        /* LCOV_EXCL_START */
        fprintf(f, "\\%%{}");
        break;
        /* LCOV_EXCL_STOP */
    case L'\\':
        fprintf(f, "\\textbackslash{}");
        break;
    case L'&':
        fprintf(f, "\\&{}");
        break;
    case L'#':
        fprintf(f, "\\#{}");
        break;
    case L'+':
        fprintf(f, "\\GreDagger{}");
        break;
    case L'_':
        fprintf(f, "\\_{}");
        break;
    case L'-':
        fprintf(f, "\\GreHyph{}");
        break;
    default:
        gregorio_print_unichar(f, to_print);
        break;
    }
    return;
}

/* a function to map the internal ST_* styles to gregoriotex styles as defined
 * in gregoriotex-syllables.tex */
static unsigned char gregoriotex_internal_style_to_gregoriotex(
        const grestyle_style style)
{
    switch (style) {
    case ST_ITALIC:
        return 1;
    case ST_BOLD:
        return 2;
    case ST_SMALL_CAPS:
        return 3;
    case ST_TT:
        return 4;
    case ST_UNDERLINED:
        return 5;
    case ST_COLORED:
        return 6;
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail2(gregoriotex_internal_style_to_gregoriotex,
                "unrecognized style: %s", grestyle_style_to_string(style));
        return 0;
        /* LCOV_EXCL_STOP */
    }
}

/*
 * A quite hacky function: when we have only one style (typically italic) and
 * when this style is on all the parts, then we return this style.
 *
 */
static grestyle_style gregoriotex_fix_style(
        const gregorio_character *current_char)
{
    grestyle_style possible_fixed_style = ST_NO_STYLE;
    grestyle_style in_fixed_style = ST_NO_STYLE;
    while (current_char) {
        if (!in_fixed_style) {
            /* before the first style */
            if (current_char->is_character) {
                /* got some character, so no future style can apply to the
                 * entire syllable */
                return ST_NO_STYLE;
            }
            if (current_char->cos.s.type == ST_T_BEGIN) {
                switch (current_char->cos.s.style) {
                case ST_VERBATIM:
                case ST_SPECIAL_CHAR:
                    /* these are pseudo-characters, and if they appear
                     * before the first style, then the style does not
                     * apply to the entire syllable */
                    return ST_NO_STYLE;

                case ST_ITALIC:
                case ST_BOLD:
                case ST_TT:
                case ST_SMALL_CAPS:
                case ST_UNDERLINED:
                case ST_COLORED:
                    if (possible_fixed_style) {
                        if (current_char->cos.s.style != possible_fixed_style) {
                            /* found a differing style */
                            return ST_NO_STYLE;
                        } else {
                            /* same style which may apply to the entire
                             * syllable */
                            in_fixed_style = possible_fixed_style;
                        }
                    } else {
                        /* we found a candidate fixed style */
                        in_fixed_style = possible_fixed_style =
                                current_char->cos.s.style;
                    }
                    break;

                default:
                    /* anything else is "transparent" before the first real
                     * or pseudo-character */
                    break;
                }
            }
            /* else it's an end of a style, which we treat as "transparent"
             * noise */
        } else {
            /* we have a possible style */
            if (!current_char->is_character) {
                if (current_char->cos.s.type == ST_T_BEGIN) {
                    switch (current_char->cos.s.style) {
                    case ST_ITALIC:
                    case ST_BOLD:
                    case ST_TT:
                    case ST_SMALL_CAPS:
                    case ST_UNDERLINED:
                    case ST_COLORED:
                        if (current_char->cos.s.style != possible_fixed_style) {
                            /* found a differing style */
                            return ST_NO_STYLE;
                        }
                        /* else it's a (nested) open of the same style, which
                         * doesn't change the style; however, nested styles
                         * (should) have been eliminated by now */
                        /* LCOV_EXCL_START */
                        gregorio_fail(gregoriotex_fix_style, "encountered a "
                                "nested style which should have been removed "
                                "by now");
                        break;
                        /* LCOV_EXCL_STOP */

                    default:
                        /* anything else is a pseudo-character or a
                         * "transparent" style, which don't affect the fixed
                         * style */
                        break;
                    }
                } else if (current_char->cos.s.type == ST_T_END) {
                    if (current_char->cos.s.style == possible_fixed_style) {
                        /* we closed the possible fixed style; we don't return
                         * yet to give it the chance to re-open */
                        in_fixed_style = ST_NO_STYLE;
                    }
                    /* else it's a close of something we don't care about or a
                     * style that wasn't opened, so for the purposes of this
                     * function, these are "transparent" and don't affect the
                     * fixed style */
                }
            }
            /* else it's a character, and that doesn't affect the fixed style */
        }
        current_char = current_char->next_character;
    }
    return possible_fixed_style;
}

/*
 * @brief Writes the translation.
 *
 * There is no special handling of translation text; that is, we just print the
 * entire string of text under the normal text line, without considering any
 * special centering or linebreaks.
 */
static __inline void write_translation(FILE *f,
        gregorio_character *translation)
{
    gregorio_not_null(translation, write_translation, return);
    gregorio_write_text(WTP_NORMAL, translation, f, &gtex_write_verb,
            &gtex_print_char, &gtex_write_begin, &gtex_write_end,
            &gtex_write_special_char);
}

/* a function to compute the height of the flat of a key
 * the flat is always on the line of the */

static char clef_flat_height(gregorio_clef clef, signed char line, bool flatted)
{
    char offset = 6;

    if (!flatted) {
        return NO_KEY_FLAT;
    }

    switch (clef) {
    case CLEF_C:
        switch (line) {
        case 1:
            offset = 2;
            break;
        case 2:
            offset = 4;
            break;
        case 3:
            offset = 6;
            break;
        case 4:
            offset = 8;
            break;
        case 5:
            offset = 10;
            break;
        default:
            /* not reachable unless there's a programming error */
            /* LCOV_EXCL_START */
            gregorio_fail2(clef_flat_height, "unknown line number: %d", line);
            break;
            /* LCOV_EXCL_STOP */
        }
        break;
    case CLEF_F:
        switch (line) {
        case 1:
            offset = 6;
            break;
        case 2:
            offset = 8;
            break;
        case 3:
            offset = 3;
            break;
        case 4:
            offset = 5;
            break;
        case 5:
            offset = 7;
            break;
        default:
            /* not reachable unless there's a programming error */
            /* LCOV_EXCL_START */
            gregorio_fail2(clef_flat_height, "unknown line number: %d", line);
            break;
            /* LCOV_EXCL_STOP */
        }
        break;
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail2(clef_flat_height, "unknown clef type: %d", clef);
        break;
        /* LCOV_EXCL_STOP */
    }

    return pitch_value(LOWEST_PITCH + offset);
}

static __inline bool is_manual_custos(const gregorio_element *const element)
{
    return element->type == GRE_CUSTOS && element->u.misc.pitched.force_pitch;
}

OFFSET_CASE(BarStandard);
OFFSET_CASE(BarVirgula);
OFFSET_CASE(BarDivisioFinalis);
OFFSET_CASE(BarParen);
OFFSET_CASE(BarVirgulaParen);

static void write_bar(FILE *f, const gregorio_score *const score,
        const gregorio_syllable *const syllable,
        const gregorio_element *const element,
        const unsigned char first_of_disc)
{
    const gregorio_bar type = element->u.misc.unpitched.info.bar;
    const gregorio_sign signs = element->u.misc.unpitched.special_sign;
    const bool is_inside_bar = element->next && !is_manual_custos(element->next)
            && element->next->type != GRE_END_OF_LINE;
    const bool has_text = !element->previous && syllable->text;
    /* the type number of function vepisemaorrare */
    const char *offset_case = BarStandard;
    signed char far_pitch_adjustment = 0;
    /* don't use "In" version of bars in the first argument of a GreDiscretionary */
    if (is_inside_bar && first_of_disc != 1) {
        fprintf(f, "\\GreIn");
    } else {
        fprintf(f, "\\Gre");
    }
    switch (type) {
    case B_VIRGULA:
        fprintf(f, "Virgula");
        offset_case = BarVirgula;
        break;
    case B_DIVISIO_MINIMA:
        fprintf(f, "DivisioMinima");
        break;
    case B_DIVISIO_MINOR:
        fprintf(f, "DivisioMinor");
        break;
    case B_DIVISIO_MAIOR:
        fprintf(f, "DivisioMaior");
        break;
    case B_DIVISIO_FINALIS:
        fprintf(f, "DivisioFinalis");
        offset_case = BarDivisioFinalis;
        break;
    case B_DIVISIO_MINOR_D1:
        fprintf(f, "Dominica{1}");
        break;
    case B_DIVISIO_MINOR_D2:
        fprintf(f, "Dominica{2}");
        break;
    case B_DIVISIO_MINOR_D3:
        fprintf(f, "Dominica{3}");
        break;
    case B_DIVISIO_MINOR_D4:
        fprintf(f, "Dominica{4}");
        break;
    case B_DIVISIO_MINOR_D5:
        fprintf(f, "Dominica{5}");
        break;
    case B_DIVISIO_MINOR_D6:
        fprintf(f, "Dominica{6}");
        break;
    case B_DIVISIO_MINOR_D7:
        fprintf(f, "Dominica{7}");
        break;
    case B_DIVISIO_MINOR_D8:
        fprintf(f, "Dominica{8}");
        break;
    case B_VIRGULA_HIGH:
        fprintf(f, "VirgulaHigh");
        offset_case = BarVirgula;
        break;
    case B_DIVISIO_MINIMA_HIGH:
        fprintf(f, "DivisioMinimaHigh");
        break;
    case B_DIVISIO_MAIOR_DOTTED:
        fprintf(f, "DivisioMaiorDotted");
        break;
    case B_DIVISIO_MINIMIS:
        fprintf(f, "DivisioMinimis");
        break;
    case B_DIVISIO_MINIMIS_HIGH:
        fprintf(f, "DivisioMinimisHigh");
        break;
    case B_VIRGULA_PAREN:
        fprintf(f, "VirgulaParen");
        offset_case = BarVirgulaParen;
        break;
    case B_VIRGULA_PAREN_HIGH:
        fprintf(f, "VirgulaParenHigh");
        offset_case = BarVirgulaParen;
        break;
    case B_DIVISIO_MINIMA_PAREN:
        fprintf(f, "DivisioMinimaParen");
        offset_case = BarParen;
        break;
    case B_DIVISIO_MINIMA_PAREN_HIGH:
        fprintf(f, "DivisioMinimaParenHigh");
        offset_case = BarParen;
        break;
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        gregorio_fail2(write_bar, "unknown bar type: %d", type);
        break;
        /* LCOV_EXCL_STOP */
    }
    fprintf(f, "{%c}", has_text? '1' : '0');
    switch (signs) {
    case _V_EPISEMA:
        fprintf(f, "{\\GreBarVEpisema{\\GreOCase%s}}", offset_case);
        break;
    case _BAR_H_EPISEMA:
        fprintf(f, "{\\GreBarBrace{\\GreOCase%s}}", offset_case);
        break;
    case _V_EPISEMA_BAR_H_EPISEMA:
        fprintf(f, "{\\GreBarBrace{\\GreOCase%s}"
                "\\GreBarVEpisema{\\GreOCase%s}}",
                offset_case, offset_case);
        break;
    default:
        fprintf(f, "{}");
        break;
    }
    switch (type) {
    case B_DIVISIO_MINIMIS_HIGH:
        ++ far_pitch_adjustment;
        /* fall through */

    case B_VIRGULA_HIGH:
    case B_VIRGULA_PAREN_HIGH:
    case B_DIVISIO_MINIMA_HIGH:
    case B_DIVISIO_MINIMA_PAREN_HIGH:
        ++ far_pitch_adjustment;
        /* fall through */

    case B_DIVISIO_MINIMIS:
        ++ far_pitch_adjustment;
        /* fall through */

    case B_VIRGULA:
    case B_VIRGULA_PAREN:
    case B_DIVISIO_MINIMA:
    case B_DIVISIO_MINIMA_PAREN:
        {
            char is_far = '0';
            const gregorio_element *e;
            const gregorio_syllable *s;
            const gregorio_glyph *g;
            const gregorio_note *n;
            signed char pitch;

            /* find the prior element */
            e = element->previous;
            if (!e) {
                for (s = syllable->previous_syllable; s; s = s->previous_syllable) {
                    /* loop to find the previous syllable with elements */
                    if (s->elements && *s->elements) {
                        for (e = *s->elements; e->next; e = e->next) {
                            /* just loop to find the last element */
                        }
                        break;
                    }
                }
            }
            if (e && e->type == GRE_ELEMENT) {
                g = e->u.first_glyph;
                if (g) {
                    while (g->next) {
                        /* loop to find the last glyph in the prior element */
                        g = g->next;
                    }
                }
                if (g && g->type == GRE_GLYPH && (n = g->u.notes.first_note)) {
                    while (n->next) {
                        /* loop to find the last note */
                        n = n->next;
                    }
                    pitch = n->u.note.pitch;
                    if (g->u.notes.liquescentia & L_DEMINUTUS && n->previous
                            && n->previous->u.note.pitch > pitch) {
                        pitch = n->previous->u.note.pitch;
                    }
                    if (pitch < score->virgula_far_pitch + far_pitch_adjustment) {
                        /* find next element */
                        e = element->next;
                        if (!e) {
                            for (s = syllable->next_syllable; s;
                                    s = s->next_syllable) {
                                /* loop to find the next syllable with elements */
                                if (s->elements && *s->elements) {
                                    e = *s->elements;
                                    break;
                                }
                            }
                        }
                        if (e) {
                            if (e->type == GRE_END_OF_LINE) {
                                is_far = '1';
                            } else if (e->type == GRE_ELEMENT) {
                                g = e->u.first_glyph;
                                if (g && g->type == GRE_GLYPH) {
                                    n = g->u.notes.first_note;
                                    if (n) {
                                        if (g->u.notes.glyph_type == G_PODATUS
                                                && n->next) {
                                            n = n->next;
                                        }
                                        if (n->u.note.pitch
                                                < score->virgula_far_pitch
                                                + far_pitch_adjustment) {
                                            is_far = '1';
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            fprintf(f, "{%c}%%\n", is_far);
        }
        break;

    default:
        fprintf(f, "%%\n");
        break;
    }
}

static __inline char *suppose_high_ledger_line(const gregorio_note *const note)
{
    return note->high_ledger_line? "\\GreSupposeHighLedgerLine" : "";
}

static __inline char *suppose_low_ledger_line(const gregorio_note *const note)
{
    return note->low_ledger_line? "\\GreSupposeLowLedgerLine" : "";
}

/*
 * ! @brief Writes augmentum duplexes (double dots) We suppose we are on the
 * last note. \n The algorithm is the following: if there is a previous note,
 * we consider that the two puncta of the augumentum duplex must correspond to
 * the last note and the previous note. If we are adding to a single note
 * glyph, which would be weird but sure why not, we just typeset two puncta
 * spaced of 2.
 */
static void write_auctum_duplex(FILE *f,
        const gregorio_note *const current_note)
{
    char pitch = current_note->u.note.pitch;
    char previous_pitch = 0;
    /* second_pitch is the second argument of the \augmentumduplex macro,
     * that's what this function is all about. */
    char second_pitch = 0;
    /* this variable will be set to 1 if we are on the note before the last
     * note of a podatus or a porrectus or a torculus resupinus */
    unsigned char special_punctum = 0;
    if (current_note->previous) {
        if (current_note->previous->u.note.pitch - current_note->u.note.pitch ==
                -1
                || current_note->previous->u.note.pitch -
                current_note->u.note.pitch == 1) {
            special_punctum = 1;
        }
        second_pitch = current_note->previous->u.note.pitch;
        previous_pitch = second_pitch;
    }

    if (!previous_pitch || previous_pitch == pitch) {
        if (is_on_a_line(pitch)) {
            second_pitch = pitch;
            special_punctum = 1;
        } else {
            second_pitch = pitch + 1;
        }
    }
    /* the first argument should always be the lowest one, that's what we do
     * here: */
    if (pitch > second_pitch) {
        previous_pitch = pitch;
        pitch = second_pitch;
        second_pitch = previous_pitch;
    }
    /* maybe the third argument should be changed */
    fprintf(f, "\\GreAugmentumDuplex{%d}{%d}{%d}%%\n", pitch_value(pitch),
            pitch_value(second_pitch), special_punctum);
}

/**
 * @brief Adds a dot.
 *
 * Writes \c \\GrePunctumMora in the gtex file, with the appropriate arguments. You might think this function
 * more straightforward than it actually is...
 */
static void write_punctum_mora(FILE *f, const gregorio_glyph *glyph,
        const gregorio_note *current_note, const int fuse_to_next_note)
{
    /* in this if we consider that the puncta are only on the last two notes
     * (maybe it would be useful to consider it more entirely, but it would be
     * really weird...) */
    /* the variable that will be set to true if we have to shift the punctum
     * inclinatum before the last note */
    bool shift_before = false;
    /* this variable will be set to 1 if we are on the note before the last
     * note of a podatus or a porrectus or a torculus resupinus */
    unsigned char special_punctum = 0;
    /* 0 if space is normal, 1 if there should be no space after a punctum */
    unsigned char no_space = 0;
    /* the pitch where to set the punctum */
    char pitch = current_note->u.note.pitch;
    /* a variable to know if we are on a punctum inclinatum or not */
    unsigned char punctum_inclinatum = 0;
    /* a temp variable */
    const gregorio_note *tmpnote;
    /* we go into this switch only if it is the note before the last note */
    if (current_note->next) {
        switch (glyph->u.notes.glyph_type) {
        case G_FLEXA:
        case G_TORCULUS:
        case G_TORCULUS_RESUPINUS_FLEXUS:
        case G_PORRECTUS_FLEXUS:
            if (!(glyph->u.notes.liquescentia & L_DEMINUTUS)) {
                shift_before = true;
            }
            if (is_between_lines(pitch)
                    && pitch - current_note->next->u.note.pitch == 1) {
                special_punctum = 2;
            }
            break;
        case G_PODATUS:
            if ((current_note->u.note.shape != S_PUNCTUM
                        && current_note->u.note.shape != S_QUILISMA)
                    || (glyph->u.notes.liquescentia
                        & (L_AUCTUS_DESCENDENS | L_AUCTUS_ASCENDENS))) {
                shift_before = true;
                /* fine tuning */
                if (current_note->next->u.note.pitch -
                        current_note->u.note.pitch == 1) {
                    if (is_on_a_line(current_note->u.note.pitch)) {
                        special_punctum = 1;
                    } else {
                        pitch = current_note->u.note.pitch - 1;
                    }
                }
            } else {
                /* case for f.g */
                if (current_note->next->u.note.pitch -
                        current_note->u.note.pitch == 1) {
                    special_punctum = 1;
                }
            }
            break;
        case G_PES_QUADRATUM:
            shift_before = true;
            if (current_note->next->u.note.pitch - current_note->u.note.pitch ==
                    1) {
                if (is_on_a_line(current_note->u.note.pitch)) {
                    special_punctum = 1;
                } else {
                    pitch = current_note->u.note.pitch - 1;
                }
            }
            break;
        case G_PORRECTUS:
        case G_TORCULUS_RESUPINUS:
            /* this case is only for the note before the previous note */
            if ((current_note->next->u.note.pitch -
                            current_note->u.note.pitch == -1
                            || current_note->next->u.note.pitch -
                            current_note->u.note.pitch == 1)
                    && !(current_note->next->next))
                special_punctum = 1;
            break;
        default:
            break;
        }
    }
    /* we enter here in any case */
    switch (glyph->u.notes.glyph_type) {
    case G_PUNCTA_INCLINATA:
    case G_2_PUNCTA_INCLINATA_DESCENDENS:
    case G_3_PUNCTA_INCLINATA_DESCENDENS:
    case G_4_PUNCTA_INCLINATA_DESCENDENS:
    case G_5_PUNCTA_INCLINATA_DESCENDENS:
    case G_TORCULUS:
        if (!current_note->next) {
            special_punctum = 1;
        }
        break;
    default:
        break;
    }
    switch (current_note->u.note.shape) {
    case S_PUNCTUM_INCLINATUM_ASCENDENS:
    case S_PUNCTUM_INCLINATUM_STANS:
    case S_PUNCTUM_INCLINATUM_DESCENDENS:
    case S_PUNCTUM_INCLINATUM_DEMINUTUS:
        punctum_inclinatum = 1;
        break;
    default:
        break;
    }
    /* when the punctum mora is on a note on a line, and the prior note is on
     * the space immediately above, the dot is placed on the space below the
     * line instead */
    if (current_note->previous
            && (current_note->previous->u.note.pitch -
                    current_note->u.note.pitch == 1)
            && is_on_a_line(current_note->u.note.pitch)
            && (current_note->previous->signs == _PUNCTUM_MORA
                    || current_note->previous->signs == _V_EPISEMA_PUNCTUM_MORA
                    || current_note->previous->choral_sign)) {
        special_punctum = 1;
    }

    if (current_note->mora_vposition) {
        special_punctum = current_note->mora_vposition == VPOS_BELOW? 1 : 0;
    }

    if (shift_before) {
        if (current_note->next->u.note.pitch - current_note->u.note.pitch == -1
                || current_note->next->u.note.pitch -
                current_note->u.note.pitch == 1) {
            fprintf(f, "\\GrePunctumMora{%d}{3}{%d}{%d}%%\n",
                    pitch_value(pitch), special_punctum, punctum_inclinatum);
        } else {
            fprintf(f, "\\GrePunctumMora{%d}{2}{%d}{%d}%%\n",
                    pitch_value(pitch), special_punctum, punctum_inclinatum);
        }
        return;
    }
    /* There are two special cases. The first: if the next glyph is a
     * ZERO_WIDTH_SPACE, and the current glyph is a PES, and the punctum mora
     * is on the first note, and the first note of the next glyph is at least
     * two (or three depending on something) pitches higher than the current
     * note.
     * You'll all have understood, this case is quite rare... but when it
     * appears, we pass 1 as a second argument of \punctummora so that it
     * removes the space introduced by the punctummora. */
    if (glyph->u.notes.glyph_type == G_PODATUS && glyph->next
            && glyph->next->type == GRE_SPACE
            && glyph->next->u.misc.unpitched.info.space == SP_ZERO_WIDTH
            && current_note->next && glyph->next->next
            && glyph->next->next->type == GRE_GLYPH
            && glyph->next->next->u.notes.first_note
            && (glyph->next->next->u.notes.first_note->u.note.pitch -
                    current_note->u.note.pitch > 1)) {
        fprintf(f, "\\GrePunctumMora{%d}{1}{%d}{%d}%%\n", pitch_value(pitch),
                special_punctum, punctum_inclinatum);
        return;
    }
    /* if there is a punctum or a auctum dumplex on a note after, we put a
     * zero-width punctum */
    tmpnote = current_note->next;
    while (tmpnote) {
        if (tmpnote->signs == _PUNCTUM_MORA || tmpnote->signs == _AUCTUM_DUPLEX
                || tmpnote->signs == _V_EPISEMA_PUNCTUM_MORA
                || tmpnote->signs == _V_EPISEMA_AUCTUM_DUPLEX
                || tmpnote->choral_sign) {
            no_space = 1;
            break;
        }
        tmpnote = tmpnote->next;
    }
    /* use a special no-space punctum mora for ascending fusion */
    if (fuse_to_next_note) {
        no_space = 1;
        if (fuse_to_next_note > 0) {
            special_punctum = 1;
        }
    }

    /* the normal operation */
    fprintf(f, "\\GrePunctumMora{%d}{%d}{%d}{%d}%%\n", pitch_value(pitch),
            no_space, special_punctum, punctum_inclinatum);
}

static __inline int get_punctum_inclinatum_space_case(
        const gregorio_note *const note)
{
    char temp;

    switch (note->u.note.shape) {
    case S_PUNCTUM_INCLINATUM_ASCENDENS:
        if (note->previous) {
            /* means that it is not the first note of the puncta inclinata
             * sequence */
            temp = note->previous->u.note.pitch - note->u.note.pitch;
            /* negative values = ascending ambitus */
            /* not sure we ever need to consider a larger ambitus here */
            switch (temp) {
            case 1:
            case 2:
            case 3:
            case 4:
                return 25;
            case -1:
            default:
                return 12;
            case -2:
                return 14;
            case -3:
            case -4:
                return 15;
            }
        }
        break;
    case S_PUNCTUM_INCLINATUM_STANS:
        if (note->previous) {
            /* means that it is not the first note of the puncta inclinata
             * sequence */
            return 26;
        }
        break;
    case S_PUNCTUM_INCLINATUM_DESCENDENS:
        if (note->previous) {
            /* means that it is not the first note of the puncta inclinata
             * sequence */
            temp = note->previous->u.note.pitch - note->u.note.pitch;
            /* negative values = ascending ambitus */
            /* not sure we ever need to consider a larger ambitus here */
            switch (temp) {
            case 1:
            default:
                return 3;
            case 2:
                return 10;
            case 3:
            case 4:
                return 11;
            case -1:
            case -2:
            case -3:
            case -4:
                return 24;
            }
        }
        break;
    case S_PUNCTUM_INCLINATUM_DEMINUTUS:
        if (note->previous) {
            /* means that it is not the first note of the puncta inclinata
             * sequence */
            temp = note->previous->u.note.pitch - note->u.note.pitch;
            if (temp < -2) {
                return 15;
            } else if (temp > 2) {
                return 11;
            } else {
                if (note->previous
                        && note->previous->u.note.shape ==
                        S_PUNCTUM_INCLINATUM_DEMINUTUS) {
                    if (temp < -1) {
                        /* really if the ambitus = 3rd at this point */
                        return 14;
                    } else if (temp > 1) {
                        /* really if the ambitus = 3rd at this point */
                        return 10;
                    } else {
                        /* temp == 0, so there is no ascending case */
                        return 8;
                    }
                } else {
                    if (temp < 0) {
                        /* puncta inclinatum followed by puncta inclinatum
                         * debilis */
                        return 13;
                    } else if (temp > 0) {
                        /* puncta inclinatum followed by puncta inclinatum
                         * debilis */
                        return 7;
                    }
                }
            }
        } /* LCOV_EXCL_LINE */
        break;
    case S_PUNCTUM_INCLINATUM_AUCTUS:
        if (note->previous) {
            /* means that it is not the first note of the puncta inclinata
             * sequence */
            temp = note->previous->u.note.pitch - note->u.note.pitch;
            if (temp < -1 || temp > 1) {
                /* this is the normal interglyph space, so we'll use it for
                 * either direction */
                return 1;
            } else {
                /* temp == 0, so there is no ascending case */
                /* we approximate that it is the same space */
                return 3;
            }
        }
        break;
    default:
        break;
    }

    return -1;
}

static __inline int get_punctum_inclinatum_to_nobar_space_case(
        const gregorio_glyph *const glyph)
{
    if (glyph->u.notes.glyph_type <= G_PUNCTA_INCLINATA) {
        const gregorio_glyph *next = gregorio_next_non_texverb_glyph(glyph);
        if (next && next->type == GRE_GLYPH
                && (next->u.notes.glyph_type == G_PUNCTUM
                    || (next->u.notes.glyph_type == G_FLEXA
                        && !next->u.notes.fuse_to_next_glyph))) {
            int descent;
            const gregorio_note *note = gregorio_glyph_last_note(glyph);
            descent = note->u.note.pitch -
                glyph->next->u.notes.first_note->u.note.pitch;
            /* a negative descent is an ascent */
            switch(descent) {
            case -1:
                return 19;
            case 1:
                return 16;
            case -2:
                return 20;
            case 2:
                return 17;
            case -3:
            case -4:
                return 21;
            case 3:
            case 4:
                return 18;
            }
        }
    }

    return -1;
}

static __inline void write_single_hepisema(FILE *const f, int hepisema_case,
        const gregorio_note *const note, gregorio_sign_orientation orientation,
        bool connect, char height, const grehepisema_size size, const int i,
        const gregorio_glyph *const glyph,
        const int porrectus_long_episema_index,
        bool (*const is_episema_shown)(const gregorio_note *))
{
    if (height) {
        const gregorio_hepisema_adjustment *adj =
                gregorio_get_hepisema_adjustment(
                        note->he_adjustment_index[orientation]);
        char ambitus = 0;
        char size_arg;

        switch (size) {
        case H_SMALL_LEFT:
            size_arg = 'l';
            connect = false;
            break;
        case H_SMALL_CENTRE:
            size_arg = 'c';
            connect = false;
            break;
        case H_SMALL_RIGHT:
            size_arg = 'r';
            break;
        default:
            size_arg = 'f';
            break;
        }

        if (i == porrectus_long_episema_index && note->next
                && is_episema_shown(note->next)) {
            ambitus = compute_ambitus(note);
        }

        if (i - 1 != porrectus_long_episema_index || !note->previous
                || !is_episema_shown(note->previous)) {
            if (connect) {
                const gregorio_glyph *next;
                if (!note->next
                        && (!(next = gregorio_next_non_texverb_glyph(glyph))
                            || next->type != GRE_SPACE
                            || next->u.misc.unpitched.info.space
                            != SP_ZERO_WIDTH)) {
                    /* not followed by a zero-width space */
                    /* try to fuse from punctum inclinatum to nobar glyph */
                    fprintf(f,
                            "\\GreHEpisemaBridge{%d}{%d}{%d}{%s%s}{%s}{%d}%%\n",
                            pitch_value(height), hepisema_case,
                            get_punctum_inclinatum_to_nobar_space_case(glyph),
                            suppose_high_ledger_line(note),
                            suppose_low_ledger_line(note),
                            adj->nudge? adj->nudge : "", adj->vbasepos);
                } else if (note->next
                        && (note->next->u.note.shape
                            == S_PUNCTUM_INCLINATUM_ASCENDENS
                            || note->next->u.note.shape
                            == S_PUNCTUM_INCLINATUM_DESCENDENS
                            || note->next->u.note.shape
                            == S_PUNCTUM_INCLINATUM_DEMINUTUS
                            || note->next->u.note.shape
                            == S_PUNCTUM_INCLINATUM_AUCTUS)) {
                    /* is a punctum inclinatum of some sort */
                    fprintf(f, "\\GreHEpisemaBridge{%d}{%d}{%d}{%s%s}{%s}{%d}%%\n",
                            pitch_value(height), hepisema_case,
                            get_punctum_inclinatum_space_case(note->next),
                            suppose_high_ledger_line(note),
                            suppose_low_ledger_line(note),
                            adj->nudge? adj->nudge : "", adj->vbasepos);
                }
            }
            fprintf(f, "\\GreHEpisema{%d}{\\GreOCase%s}{%d}{%d}{%c}{%d}"
                    "{%s%s}{%s}{%d}%%\n", pitch_value(height),
                    note->gtex_offset_case, ambitus, hepisema_case, size_arg,
                    pitch_value(height), suppose_high_ledger_line(note),
                    suppose_low_ledger_line(note), adj->nudge? adj->nudge : "",
                    adj->vbasepos);
        }
    }
}

/**
 * @brief A function that writes the good \c \\hepisema in GregorioTeX.
 * @param i The position of the note in the glyph.
 */
static void gregoriotex_write_hepisema(FILE *const f,
        const gregorio_note *const note, const int i, const gtex_type type,
        const gregorio_glyph *const glyph)
{
    int porrectus_long_episema_index = -1;

    gregorio_assert(note, gregoriotex_write_hepisema,
            "called with NULL pointer", return);

    switch (type) {
    case T_PORRECTUS:
    case T_PORRECTUS_FLEXUS:
        porrectus_long_episema_index = 1;
        break;
    case T_TORCULUS_RESUPINUS:
    case T_TORCULUS_RESUPINUS_FLEXUS:
        porrectus_long_episema_index = 2;
        break;
    default:
        /* do nothing */
        break;
    }

    write_single_hepisema(f, 1, note, SO_UNDER, note->h_episema_below_connect,
            note->h_episema_below, note->h_episema_below_size, i, glyph,
            porrectus_long_episema_index, &gtex_is_h_episema_below_shown);
    write_single_hepisema(f, 0, note, SO_OVER, note->h_episema_above_connect,
            note->h_episema_above, note->h_episema_above_size, i, glyph,
            porrectus_long_episema_index, &gtex_is_h_episema_above_shown);
}

/* a macro to write an additional line */

static void write_additional_line(FILE *f, int i, gtex_type type, bool bottom,
        const gregorio_note *current_note, const gregorio_score *const score)
{
    char ambitus = 0;
    gregorio_assert(current_note, write_additional_line, "called with no note",
            return);
    /* patch to get a line under the full glyph in the case of dbc (for
     * example) */
    switch (type) {
    case T_PORRECTUS:
    case T_PORRECTUS_FLEXUS:
        switch (i) {
        case 1:
            i = HEPISEMA_FIRST_TWO;
            break;
        case 2:
            if (current_note->previous->u.note.pitch > LOW_LEDGER_LINE_PITCH
                    && current_note->previous->u.note.pitch
                    < score->high_ledger_line_pitch) {
                i = HEPISEMA_FIRST_TWO;
                /* HEPISEMA_FIRST_TWO works only for first note */
                current_note = current_note->previous;
            } else {
                return;
            }
            break;
        case 3:
            if (bottom || current_note->previous->u.note.pitch
                    >= score->high_ledger_line_pitch) {
                /* we don't need to add twice the same line */
                return;
            }
            break;
        }
        break;
    case T_TORCULUS_RESUPINUS:
    case T_TORCULUS_RESUPINUS_FLEXUS:
        switch (i) {
        case 2:
            i = HEPISEMA_FIRST_TWO;
            break;
        case 3:
            if (current_note->previous->u.note.pitch > LOW_LEDGER_LINE_PITCH
                    && current_note->previous->u.note.pitch
                    < score->high_ledger_line_pitch) {
                i = HEPISEMA_FIRST_TWO;
                /* HEPISEMA_FIRST_TWO works only for first note */
                current_note = current_note->previous;
            } else {
                return;
            }
            break;
        case 4:
            if (bottom || current_note->previous->u.note.pitch
                    >= score->high_ledger_line_pitch) {
                /* we don't need to add twice the same line */
                return;
            }
            break;
        }
        break;
    default:
        break;
    }

    if (i == HEPISEMA_FIRST_TWO) {
        /* here we must compare the first note of the big bar with the second
         * one, but it may be tricky sometimes, because of the previous patch */
        gregorio_assert_only(!current_note->previous ||
                current_note->u.note.pitch
                > current_note->previous->u.note.pitch,
                write_additional_line, "HEPISEMA_FIRST_TWO on the wrong note");
        ambitus = current_note->u.note.pitch - current_note->next->u.note.pitch;
    }
    fprintf(f, "\\GreAdditionalLine{\\GreOCase%s}{%d}{%d}%%\n",
            current_note->gtex_offset_case, ambitus, bottom ? 3 : 2);
}

/*
 *
 * a function that writes the good value of \vepisema in GregorioTeX. i is the
 * position of the note in the glyph
 *
 */

static void write_vepisema(FILE *f, const gregorio_note *const note)
{
    fprintf(f, "\\GreVEpisema{%d}{\\GreOCase%s}%%\n",
            pitch_value(note->v_episema_height), note->gtex_offset_case);
}

/*
 * a function that writes the rare signs in GregorioTeX. i is the position of
 * the note in the glyph */

static void write_rare_sign(FILE *f, const gregorio_note *const current_note,
        const gregorio_sign rare)
{
    switch (rare) {
    case _ACCENTUS:
        fprintf(f, "\\GreAccentus{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _ACCENTUS_REVERSUS:
        fprintf(f, "\\GreReversedAccentus{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _CIRCULUS:
        fprintf(f, "\\GreCirculus{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _SEMI_CIRCULUS:
        fprintf(f, "\\GreSemicirculus{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _SEMI_CIRCULUS_REVERSUS:
        fprintf(f, "\\GreReversedSemicirculus{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _MUSICA_FICTA_FLAT:
        fprintf(f, "\\GreMusicaFictaFlat{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _MUSICA_FICTA_NATURAL:
        fprintf(f, "\\GreMusicaFictaNatural{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
    case _MUSICA_FICTA_SHARP:
        fprintf(f, "\\GreMusicaFictaSharp{%d}{\\GreOCase%s}%%\n",
                pitch_value(current_note->u.note.pitch),
                current_note->gtex_offset_case);
        break;
        /* the cases of the bar signs are dealt in another function
         * (write_bar) */
    default:
        /* not reachable unless there's a programming error */
        /* LCOV_EXCL_START */
        assert(false);
        break;
        /* LCOV_EXCL_STOP */
    }
}

static __inline const char *alteration_name(
        const gregorio_shape next_note_alteration)
{
    switch (next_note_alteration) {
    case S_FLAT:
        return "Flat";
    case S_FLAT_PAREN:
        return "FlatParen";
    case S_SHARP:
        return "Sharp";
    case S_SHARP_PAREN:
        return "SharpParen";
    case S_NATURAL:
        return "Natural";
    case S_NATURAL_PAREN:
        return "NaturalParen";
    default:
        return "";
    }
}

static const char *next_custos(const signed char next_note_pitch,
        const gregorio_shape next_note_alteration,
        gregoriotex_status *const status)
{
    static char buf[50];

    gregorio_snprintf(buf, sizeof buf, "%s\\GreNextCustos{%d}{%s}",
            status->suppressed_custos? "\\GreResetEolCustos" : "",
            pitch_value(next_note_pitch),
            alteration_name(next_note_alteration));

    status->suppressed_custos = false;

    return buf;
}

/*
 * function used when the glyph is only one note long
 */

static void write_note(FILE *f, gregorio_note *note,
        const gregorio_glyph *glyph, const char next_note_pitch,
        const gregorio_shape next_note_alteration,
        gregoriotex_status *const status)
{
    unsigned int initial_shape = note->u.note.shape;
    const char *shape;
    int space_case;
    static char cpbuf[96];
    /* type in the sense of GregorioTeX alignment type */
    gtex_alignment type = AT_ONE_NOTE;
    gregorio_assert(note, write_note, "called with NULL pointer",
            return);
    if (note->u.note.shape == S_PUNCTUM) {
        switch (note->u.note.liquescentia) {
        case L_AUCTUS_ASCENDENS:
            note->u.note.shape = S_PUNCTUM_AUCTUS_ASCENDENS;
            break;
        case L_AUCTUS_DESCENDENS:
            note->u.note.shape = S_PUNCTUM_AUCTUS_DESCENDENS;
            break;
        case L_INITIO_DEBILIS:
            if (glyph->u.notes.fuse_to_next_glyph > 0) {
                break;
            }
            /* fall through */
        case L_DEMINUTUS:
            /* this is a currenly unused, but we keep it as a fallback case */
            /* LCOV_EXCL_START */
            note->u.note.shape = S_PUNCTUM_DEMINUTUS;
            break;
            /* LCOV_EXCL_STOP */
        default:
            break;
        }
    }
    shape = determine_note_glyph_name(note, glyph, &type);
    note->u.note.shape = initial_shape;
    /* special things for puncta inclinata */
    space_case = get_punctum_inclinatum_space_case(note);
    if (space_case >= 0) {
        fprintf(f, "\\GreEndOfGlyph{%d}%%\n", space_case);
    }

    switch (note->u.note.shape) {
    case S_FLAT:
    case S_FLAT_PAREN:
    case S_NATURAL:
    case S_NATURAL_PAREN:
    case S_SHARP:
    case S_SHARP_PAREN:
        fprintf(f, "\\Gre%s{%d}{0}", alteration_name(note->u.note.shape),
                pitch_value(note->u.note.pitch));
        break;
    default:
        fprintf(f, "\\GreGlyph{%s}{%d}{%s}{%d}",
                code_point(shape, glyph->u.notes.is_cavum, cpbuf, sizeof cpbuf),
                pitch_value(note->u.note.pitch),
                next_custos(next_note_pitch, next_note_alteration, status),
                type);
        break;
    }
}

static void syllable_first_type(gregorio_syllable *syllable,
        gtex_alignment *type, gtex_alteration *alteration)
{
    gtex_type gtype = T_ONE_NOTE;
    /* alteration says if there is a flat or a natural first in the next
     * syllable, see gregoriotex.tex for more details */
    gregorio_glyph *glyph;
    gregorio_element *element;
    gregorio_assert(type && alteration && syllable && syllable->elements,
            syllable_first_type, "called with a NULL argument", return);
    *type = AT_ONE_NOTE;
    *alteration = ALT_NONE;
    for (element = syllable->elements[0]; element; element = element->next) {
        if (element->type == GRE_BAR) {
            switch (element->u.misc.unpitched.info.bar) {
            case B_VIRGULA:
            case B_VIRGULA_HIGH:
                *type = AT_VIRGULA;
                break;
            case B_VIRGULA_PAREN:
            case B_VIRGULA_PAREN_HIGH:
                *type = AT_VIRGULA_PAREN;
                break;
            case B_DIVISIO_MINIMIS:
            case B_DIVISIO_MINIMIS_HIGH:
            case B_DIVISIO_MINIMA:
            case B_DIVISIO_MINIMA_HIGH:
                *type = AT_DIVISIO_MINIMA;
                break;
            case B_DIVISIO_MINIMA_PAREN:
            case B_DIVISIO_MINIMA_PAREN_HIGH:
                *type = AT_DIVISIO_MINIMA_PAREN;
                break;
            case B_DIVISIO_MINOR:
                *type = AT_DIVISIO_MINOR;
                break;
            case B_DIVISIO_MAIOR:
            case B_DIVISIO_MAIOR_DOTTED:
                *type = AT_DIVISIO_MAIOR;
                break;
            case B_DIVISIO_MINOR_D1:
            case B_DIVISIO_MINOR_D2:
            case B_DIVISIO_MINOR_D3:
            case B_DIVISIO_MINOR_D4:
            case B_DIVISIO_MINOR_D5:
            case B_DIVISIO_MINOR_D6:
            case B_DIVISIO_MINOR_D7:
            case B_DIVISIO_MINOR_D8:
                *type = AT_DIVISIO_DOMINICAN;
                break;
            case B_DIVISIO_FINALIS:
                *type = AT_DIVISIO_FINALIS;
                break;
            default:
                /* not reachable unless there's a programming error */
                /* LCOV_EXCL_START */
                gregorio_fail(syllable_first_type, "invalid bar");
                *type = AT_ONE_NOTE;
                break;
                /* LCOV_EXCL_STOP */
            }
            *alteration = ALT_NONE;
            return;
        }
        if (element->type == GRE_ELEMENT && element->u.first_glyph) {
            for (glyph = element->u.first_glyph; glyph; glyph = glyph->next) {
                if (glyph->type == GRE_GLYPH && glyph->u.notes.first_note) {
                    switch (glyph->u.notes.glyph_type) {
                    case G_ALTERATION:
                        if (*alteration == ALT_NONE) {
                            switch (glyph->u.notes.first_note->u.note.shape) {
                            case S_FLAT:
                                *alteration = ALT_FLAT;
                                break;
                            case S_FLAT_PAREN:
                                *alteration = ALT_FLAT_PAREN;
                                break;
                            case S_NATURAL:
                                *alteration = ALT_NATURAL;
                                break;
                            case S_NATURAL_PAREN:
                                *alteration = ALT_NATURAL_PAREN;
                                break;
                            case S_SHARP:
                                *alteration = ALT_SHARP;
                                break;
                            case S_SHARP_PAREN:
                                *alteration = ALT_SHARP_PAREN;
                                break;
                            default:
                                /* not reachable unless there's a programming error */
                                /* LCOV_EXCL_START */
                                gregorio_fail(syllable_first_type,
                                        "invalid alteration");
                                break;
                                /* LCOV_EXCL_STOP */
                            }
                        }
                        continue;
                    case G_PUNCTA_INCLINATA:
                    case G_2_PUNCTA_INCLINATA_DESCENDENS:
                    case G_3_PUNCTA_INCLINATA_DESCENDENS:
                    case G_4_PUNCTA_INCLINATA_DESCENDENS:
                    case G_5_PUNCTA_INCLINATA_DESCENDENS:
                    case G_2_PUNCTA_INCLINATA_ASCENDENS:
                    case G_3_PUNCTA_INCLINATA_ASCENDENS:
                    case G_4_PUNCTA_INCLINATA_ASCENDENS:
                    case G_5_PUNCTA_INCLINATA_ASCENDENS:
                    case G_PUNCTUM:
                    case G_STROPHA:
                    case G_VIRGA:
                    case G_VIRGA_REVERSA:
                    case G_STROPHA_AUCTA:
                    case G_DISTROPHA:
                    case G_DISTROPHA_AUCTA:
                    case G_TRISTROPHA:
                    case G_TRISTROPHA_AUCTA:
                    case G_BIVIRGA:
                    case G_TRIVIRGA:
                        determine_note_glyph_name
                                (glyph->u.notes.first_note, glyph, type);
                        break;
                    default:
                        gregoriotex_determine_glyph_name(glyph, type, &gtype);
                        break;
                    }
                    return;
                }
            }
        }
    }
    if (syllable->elements[0]) {
        /* if there is anything else in the next syllable */
        *alteration = ALT_NONE;
        *type = AT_ONE_NOTE;
        return;
    }
    /* the only thing that should reach this point is an empty next syllable
     * we treat that kind of syllable as a bar */
    *alteration = ALT_NONE;
    *type = AT_EMPTY_SYLLABLE;
    return;
}

static __inline void write_low_choral_sign(FILE *const f,
        const gregorio_note *const note, int special)
{
    if (note->choral_sign_is_nabc) {
        fprintf(f, "\\GreLowChoralSign{%d}{\\GreNABCChar{",
                pitch_value(note->u.note.pitch));
        tex_escape_text(f, note->choral_sign);
        fprintf(f, "}}{%d}%%\n", special);
    } else {
        fprintf(f, "\\GreLowChoralSign{%d}{%s}{%d}%%\n",
                pitch_value(note->u.note.pitch), note->choral_sign,
                special);
    }
}

static __inline void write_high_choral_sign(FILE *const f,
        const gregorio_note *const note, int pitch_offset)
{
    if (note->choral_sign_is_nabc) {
        fprintf(f, "\\GreHighChoralSign{%d}{\\GreNABCChar{",
                pitch_value(note->u.note.pitch + pitch_offset));
        tex_escape_text(f, note->choral_sign);
        fprintf(f, "}}{\\GreOCase%s}%%\n", note->gtex_offset_case);
    } else {
        fprintf(f, "\\GreHighChoralSign{%d}{%s}{\\GreOCase%s}%%\n",
                pitch_value(note->u.note.pitch + pitch_offset),
                note->choral_sign, note->gtex_offset_case);
    }
}

static void write_choral_sign(FILE *f, const gregorio_glyph *glyph,
        const gregorio_note *current_note, bool low)
{
    bool kind_of_pes;
    /* false in the normal case (sign above the note), true in the case of it's
     * next to the note (same height as a punctum) */
    bool low_sign = choral_sign_here_is_low(glyph, current_note, &kind_of_pes);

    /* the low choral signs must be typeset after the punctum, whereas the high
     * must be typeset before the h episema */
    if ((low_sign && !low) || (!low_sign && low)) {
        return;
    }

    if (low_sign) {
        /* very approximative heuristic, some things may have to be adapted
         * here... */
        if (is_on_a_line(current_note->u.note.pitch)) {
            if (kind_of_pes && current_note->u.note.pitch -
                    current_note->next->u.note.pitch == -1) {
                write_low_choral_sign(f, current_note, 1);
                return;
            }
            if (current_note->previous
                    && (current_note->previous->signs == _PUNCTUM_MORA
                            || current_note->previous->signs ==
                            _V_EPISEMA_PUNCTUM_MORA)) {
                write_low_choral_sign(f, current_note, 1);
                return;
            }
        }

        write_low_choral_sign(f, current_note, 0);
    } else {
        /* let's cheat a little */
        if (is_on_a_line(current_note->u.note.pitch)) {
            write_high_choral_sign(f, current_note, 0);
        } else {
            write_high_choral_sign(f, current_note, 2);
        }
    }
}

/*
 *
 * A function that write the signs of a glyph, which has the type type (T_*,
 * not G_*, which is in the glyph->glyph_type), and (important), we start only
 * at the note current_note. It is due to the way we call it : if type is
 * T_ONE_NOTE, we just do the signs on current_note, not all. This is the case
 * for example for the first note of the torculus resupinus, or the
 * G_*_PUNCTA_INCLINATA.
 *
 */

/* small helper */
static __inline bool _found(FILE *const f, const bool found)
{
    if (!found) {
        fprintf (f, "%%\n");\
        return true;
    }
    return found;
}

static void compute_height_extrema(const gregorio_glyph *const glyph,
        const gregorio_note *note, signed char *const top_height,
        signed char *const bottom_height)
{
    char height;
    /* get the minima/maxima pitches */
    for (; note; note = note->next) {
        if (note->h_episema_above) {
            height = note->h_episema_above;
        } else {
            if (note->v_episema_height && note->v_episema_height
                    > note->u.note.pitch) {
                height = note->v_episema_height;
            } else {
                height = note->u.note.pitch;
            }

            if (note->choral_sign
                    && !choral_sign_here_is_low(glyph, note, NULL)) {
                ++height;
            }
        }
        if (*top_height == UNDETERMINED_HEIGHT || height > *top_height) {
            *top_height = height;
        }

        if (note->h_episema_below) {
            height = note->h_episema_below;
        } else if (note->v_episema_height && note->v_episema_height
                < note->u.note.pitch) {
            height = note->v_episema_height;
        } else {
            height = note->u.note.pitch;

            /* no vertical episema, so we need to check for a stem */
            gregorio_assert(glyph->type == GRE_GLYPH, compute_height_extrema,
                    "glyph->type must be GRE_GLYPH here", return);
            switch (glyph->u.notes.glyph_type) {
            case G_BIVIRGA:
            case G_TRIVIRGA:
            case G_VIRGA:
            case G_VIRGA_REVERSA:
                --height;
                break;

            case G_PUNCTUM:
                switch (note->u.note.shape) {
                case S_ORISCUS_SCAPUS_ASCENDENS:
                case S_ORISCUS_SCAPUS_DESCENDENS:
                    --height;
                    break;

                default:
                    /* default to avoid the warning */
                    break;
                }
                break;

            default:
                /* default to avoid the warning */

                /* other shapes like the porrectus have stems, but the height
                 * computation will cover other notes in the shape, negating
                 * the need to account for the stem on the shape */
                break;
            }
        }

        if (*bottom_height == UNDETERMINED_HEIGHT || height < *bottom_height) {
            *bottom_height = height;
        }
    }
}

static void compute_element_height_extrema(
        const gregorio_element *const element, signed char *const top_height,
        signed char *const bottom_height)
{
    const gregorio_glyph *glyph;
    gregorio_not_null(element, compute_element_height_extrema, return);
    if (element->type != GRE_ELEMENT) {
        return;
    }
    /* get the minima/maxima pitches */
    for (glyph = element->u.first_glyph; glyph; glyph = glyph->next) {
        if (glyph->type == GRE_GLYPH) {
            compute_height_extrema(glyph, glyph->u.notes.first_note,
                    top_height, bottom_height);
        }
    }
}

static __inline void fixup_height_extrema(signed char *const top_height,
        signed char *const bottom_height)
{
    if (*top_height == UNDETERMINED_HEIGHT) {
        *top_height = 9; /* 'g' */
    }
    if (*bottom_height == UNDETERMINED_HEIGHT) {
        *bottom_height = 9; /* 'g' */
    }
}

static __inline bool is_ledger_drawn(const bool setting,
        const gregorio_ledger_specificity specificity)
{
    return ((specificity & LEDGER_DRAWN) && setting);
}

static void write_signs(FILE *f, gtex_type type,
        const gregorio_glyph *glyph, const gregorio_note *note,
        int fuse_to_next_note, gregoriotex_status *const status,
        const gregorio_score *const score)
{
    /* i is the number of the note for which we are typesetting the sign. */
    int i;
    const gregorio_note *current_note;
    signed char high_pitch = UNDETERMINED_HEIGHT;
    signed char low_pitch = UNDETERMINED_HEIGHT;
    bool found = false;
    compute_height_extrema(glyph, note, &high_pitch, &low_pitch);
    fixup_height_extrema(&high_pitch, &low_pitch);
    fprintf(f, "%%\n{%%\n\\GreGlyphHeights{%d}{%d}%%\n",
            pitch_value(high_pitch), pitch_value(low_pitch));
    for (current_note = note, i = 1; current_note;
            current_note = current_note->next, ++i) {
        /* we start by the additional lines */
        if (is_ledger_drawn(current_note->low_ledger_line,
                current_note->low_ledger_specificity)) {
            write_additional_line(f, i, type, true, current_note, score);
            status->bottom_line = 1;
        }
        if (is_ledger_drawn(current_note->high_ledger_line,
                current_note->high_ledger_specificity)) {
            write_additional_line(f, i, type, false, current_note, score);
        }
        if (current_note->texverb) {
            fprintf(f, "%% verbatim text at note level:\n%s%%\n"
                    "%% end of verbatim text\n",
                    gregorio_texverb(current_note->texverb));
        }
        if (type == T_ONE_NOTE) {
            break;
        }
    }
    fprintf(f, "}{");
    /* now a first loop for the choral signs, because high signs must be taken
     * into account before any hepisema */
    for (current_note = note, i = 1; current_note;
            current_note = current_note->next, ++i) {
        if (current_note->choral_sign) {
            found = _found(f, found);
            write_choral_sign(f, glyph, current_note, false);
        }
        if (type == T_ONE_NOTE) {
            break;
        }
    }
    /* a loop for rare signs, vertical episema, and horizontal episema */
    for (current_note = note, i = 1; current_note;
            current_note = current_note->next, ++i) {
        /* we continue with the hepisema */
        if (current_note->h_episema_above || current_note->h_episema_below) {
            found = _found(f, found);
            gregoriotex_write_hepisema(f, current_note, i, type, glyph);
        }
        /* write_rare_sign also writes the vepisema */
        if (current_note->special_sign) {
            found = _found(f, found);
            write_rare_sign(f, current_note, current_note->special_sign);
        }
        if (current_note->signs != _NO_SIGN) {
            found = _found(f, found);
        }
        switch (current_note->signs) {
        case _V_EPISEMA:
        case _V_EPISEMA_PUNCTUM_MORA:
        case _V_EPISEMA_AUCTUM_DUPLEX:
            write_vepisema(f, current_note);
            break;
        default:
            /* do nothing */
            break;
        }
        if (type == T_ONE_NOTE) {
            break;
        }
    }
    /* final loop for choral signs and punctum mora */
    for (current_note = note, i = 1; current_note;
            current_note = current_note->next, ++i) {
        switch (current_note->signs) {
        case _PUNCTUM_MORA:
        case _V_EPISEMA_PUNCTUM_MORA:
            write_punctum_mora(f, glyph, current_note, fuse_to_next_note);
            break;
        case _AUCTUM_DUPLEX:
        case _V_EPISEMA_AUCTUM_DUPLEX:
            write_auctum_duplex(f, current_note);
            break;
        default:
            break;
        }
        if (current_note->choral_sign) {
            found = _found(f, found);
            write_choral_sign(f, glyph, current_note, true);
        }
        if (type == T_ONE_NOTE) {
            break;
        }
    }
    fprintf(f, "}{");
    if (status->point_and_click) {
        fprintf(f, "%u:%u:%u", note->src_line, note->src_offset,
                note->src_column + 1);
    }
    fprintf(f, "}%%\n");
}

static char *determine_leading_shape(const gregorio_glyph *const glyph)
{
    static char buf[BUFSIZE];
    int ambitus = compute_ambitus(glyph->u.notes.first_note);
    const char *head, *head_liquescence;

    switch (glyph->u.notes.first_note->u.note.shape) {
    case S_QUILISMA:
        head = "Quilisma";
        break;
    case S_ORISCUS_ASCENDENS:
    case S_ORISCUS_DESCENDENS:
        head = "Oriscus";
        break;
    default:
        head = "Punctum";
        break;
    }

    if (glyph->u.notes.liquescentia & L_INITIO_DEBILIS) {
        head_liquescence = "InitioDebilis";
    } else {
        head_liquescence = "";
    }

    gregorio_snprintf(buf, BUFSIZE, "Leading%s%s%s", head, tex_ambitus[ambitus],
            head_liquescence);
    return buf;
}

static __inline void write_composed_multinote_glyph(FILE *const f,
        gregorio_note *current_note, const gregorio_glyph *glyph,
        const signed char next_note_pitch,
        const gregorio_shape next_note_alteration,
        const int fuse_to_next_note, gregoriotex_status *const status,
        const gregorio_score *const score, const char *glyph_end_between_notes)
{
    while (current_note) {
        const bool has_next = current_note->next != NULL;
        if (has_next) {
            write_note(f, current_note, glyph, current_note->next->u.note.pitch,
                    S_UNDETERMINED, status);
        } else {
            write_note(f, current_note, glyph, next_note_pitch,
                    next_note_alteration, status);
        }
        write_signs(f, T_ONE_NOTE, glyph, current_note,
                has_next ? 0 : fuse_to_next_note, status, score);
        current_note = current_note->next;
        if (current_note && glyph_end_between_notes) {
            fputs(glyph_end_between_notes, f);
        }
    }
}

static void write_glyph(FILE *const f, const gregorio_syllable *const syllable,
        const gregorio_element *const element,
        gregorio_glyph *const glyph,
        gregoriotex_status *const status, const gregorio_score *const score)
{
    static char cpbuf[96], cpbuf2[96];
    /* type is the type of the glyph. Understand the type of the glyph for
     * gregoriotex, for the alignement between text and notes. (AT_ONE_NOTE,
     * etc.) */
    gtex_alignment type = 0;
    /* the type of the glyph, in the sense of the shape (T_PES, etc.) */
    gtex_type gtype = 0;
    signed char next_note_pitch = 0;
    gregorio_note *current_note;
    const char *leading_shape, *shape;
    const gregorio_glyph *prev_glyph =
            gregorio_previous_non_texverb_glyph(glyph);
    int fuse_to_next_note, fuse_from_previous_note =
            (prev_glyph && prev_glyph->type == GRE_GLYPH)
            ? prev_glyph->u.notes.fuse_to_next_glyph : 0;
    gregorio_shape next_note_alteration;
    gregorio_assert(glyph, write_glyph, "called with NULL pointer", return);
    gregorio_assert(glyph->type == GRE_GLYPH && glyph->u.notes.first_note,
            write_glyph, "called with glyph without note", return);
    fuse_to_next_note = glyph->u.notes.fuse_to_next_glyph;
    if (fuse_from_previous_note) {
        fprintf(f, "\\GreFuse");
    }
    next_note_pitch = gregorio_determine_next_pitch(syllable, element, glyph,
            &next_note_alteration);
    current_note = glyph->u.notes.first_note;
    /* first we check if it is really a unique glyph in gregoriotex... the
     * glyphs that are not a unique glyph are : trigonus and pucta inclinata
     * in general, and torculus resupinus and torculus resupinus flexus, so
     * we first divide the glyph into real gregoriotex glyphs */
    switch (glyph->u.notes.glyph_type) {
    case G_PUNCTA_INCLINATA:
    case G_2_PUNCTA_INCLINATA_DESCENDENS:
    case G_3_PUNCTA_INCLINATA_DESCENDENS:
    case G_4_PUNCTA_INCLINATA_DESCENDENS:
    case G_5_PUNCTA_INCLINATA_DESCENDENS:
    case G_2_PUNCTA_INCLINATA_ASCENDENS:
    case G_3_PUNCTA_INCLINATA_ASCENDENS:
    case G_4_PUNCTA_INCLINATA_ASCENDENS:
    case G_5_PUNCTA_INCLINATA_ASCENDENS:
        write_composed_multinote_glyph(f, current_note, glyph,
                next_note_pitch, next_note_alteration, fuse_to_next_note,
                status, score, NULL);
        break;
    case G_SCANDICUS:
        if ((glyph->u.notes.liquescentia & L_DEMINUTUS)
                || glyph->u.notes.liquescentia == L_NO_LIQUESCENTIA
                || glyph->u.notes.liquescentia == L_FUSED) {
            shape = gregoriotex_determine_glyph_name(glyph, &type, &gtype);
            fprintf(f, "\\GreGlyph{%s}{%d}{%s}{%d}", code_point(shape,
                        glyph->u.notes.is_cavum, cpbuf, sizeof cpbuf),
                    pitch_value(glyph->u.notes.first_note->u.note.pitch),
                    next_custos(next_note_pitch, next_note_alteration, status),
                    type);
            write_signs(f, gtype, glyph, glyph->u.notes.first_note,
                    fuse_to_next_note, status, score);
        } else {
            write_composed_multinote_glyph(f, current_note, glyph,
                    next_note_pitch, next_note_alteration, fuse_to_next_note,
                    status, score, NULL);
        }
        break;
    case G_ANCUS:
        gregorio_assert(glyph->u.notes.liquescentia & L_DEMINUTUS,
                write_glyph, "encountered a non-deminutus ancus", break);
        shape = gregoriotex_determine_glyph_name(glyph, &type, &gtype);
        fprintf(f, "\\GreGlyph{%s}{%d}{%s}{%d}", code_point(shape,
                        glyph->u.notes.is_cavum, cpbuf, sizeof cpbuf),
                pitch_value(glyph->u.notes.first_note->u.note.pitch),
                next_custos(next_note_pitch, next_note_alteration, status),
                type);
        write_signs(f, gtype, glyph, glyph->u.notes.first_note,
                fuse_to_next_note, status, score);
        break;
    case G_TORCULUS_RESUPINUS_FLEXUS:
        /* we retain this "old-style" fusion as it does look marginally better
         * on screen */
        leading_shape = determine_leading_shape(glyph);
        /* trick to have the good position for these glyphs */
        glyph->u.notes.glyph_type = G_PORRECTUS_FLEXUS_NO_BAR;
        glyph->u.notes.first_note = current_note->next;
        shape = gregoriotex_determine_glyph_name(glyph, &type, &gtype);
        fprintf(f, "\\GreGlyph{\\GreFuseTwo{%s}{%s}}{%d}{%s}{%d}",
                code_point(leading_shape, glyph->u.notes.is_cavum, cpbuf,
                    sizeof cpbuf),
                code_point(shape, glyph->u.notes.is_cavum, cpbuf2,
                    sizeof cpbuf2),
                pitch_value(glyph->u.notes.first_note->u.note.pitch),
                next_custos(next_note_pitch, next_note_alteration, status),
                type);
        glyph->u.notes.first_note = current_note;
        glyph->u.notes.glyph_type = G_TORCULUS_RESUPINUS_FLEXUS;
        write_signs(f, gtype, glyph, glyph->u.notes.first_note,
                fuse_to_next_note, status, score);
        break;
    case G_BIVIRGA:
    case G_TRIVIRGA:
        write_composed_multinote_glyph(f, current_note, glyph,
                next_note_pitch, next_note_alteration, fuse_to_next_note,
                status, score, "\\GreEndOfGlyph{4}%%\n");
        break;
    case G_TRISTROPHA:
    case G_TRISTROPHA_AUCTA:
    case G_DISTROPHA:
    case G_DISTROPHA_AUCTA:
        write_composed_multinote_glyph(f, current_note, glyph,
                next_note_pitch, next_note_alteration, fuse_to_next_note,
                status, score, "\\GreEndOfGlyph{5}%%\n");
        break;

    case G_PUNCTUM:
        switch (glyph->u.notes.first_note->u.note.shape) {
        case S_ORISCUS_ASCENDENS:
        case S_ORISCUS_DESCENDENS:
        case S_ORISCUS_DEMINUTUS:
        case S_ORISCUS_SCAPUS_ASCENDENS:
        case S_ORISCUS_SCAPUS_DESCENDENS:
            /* don't change the oriscus */
            break;

        default:
            switch (glyph->u.notes.liquescentia) {
            case L_AUCTUS_ASCENDENS:
                glyph->u.notes.first_note->u.note.shape =
                        S_PUNCTUM_AUCTUS_ASCENDENS;
                break;
            case L_AUCTUS_DESCENDENS:
                glyph->u.notes.first_note->u.note.shape =
                        S_PUNCTUM_AUCTUS_DESCENDENS;
                break;
            case L_INITIO_DEBILIS:
            if (glyph->u.notes.fuse_to_next_glyph > 0) {
                break;
            }
            /* fall through */
            case L_DEMINUTUS:
                glyph->u.notes.first_note->u.note.shape = S_PUNCTUM_DEMINUTUS;
            default:
                break;
            }
            break;
        }

        /* fall through */
    case G_PUNCTUM_INCLINATUM:
    case G_VIRGA:
    case G_VIRGA_REVERSA:
    case G_STROPHA:
    case G_STROPHA_AUCTA:
    case G_ALTERATION:
        write_note(f, glyph->u.notes.first_note, glyph, next_note_pitch,
                next_note_alteration, status);
        write_signs(f, T_ONE_NOTE, glyph, current_note, fuse_to_next_note,
                status, score);
        break;
    default:
        /* we retain this "old-style" fusion as it does look marginally better
         * on screen */
        /* special case of the torculus resupinus which first note is not a
         * punctum */
        if (glyph->u.notes.glyph_type == G_TORCULUS_RESUPINUS
                && current_note->u.note.shape != S_PUNCTUM
                && current_note->u.note.shape != S_QUILISMA) {
            leading_shape = determine_leading_shape(glyph);
            /* trick to have the good position for these glyphs */
            glyph->u.notes.glyph_type = G_PORRECTUS_NO_BAR;
            glyph->u.notes.first_note = current_note->next;
            shape = gregoriotex_determine_glyph_name(glyph, &type, &gtype);
            fprintf(f, "\\GreGlyph{\\GreFuseTwo{%s}{%s}}{%d}{%s}{%d}",
                    code_point(leading_shape, glyph->u.notes.is_cavum, cpbuf,
                        sizeof cpbuf),
                    code_point(shape, glyph->u.notes.is_cavum, cpbuf2,
                        sizeof cpbuf2),
                    pitch_value(glyph->u.notes.first_note->u.note.pitch),
                    next_custos(next_note_pitch, next_note_alteration, status),
                    type);
            glyph->u.notes.first_note = current_note;
            glyph->u.notes.glyph_type = G_TORCULUS_RESUPINUS;
            write_signs(f, gtype, glyph, glyph->u.notes.first_note,
                    fuse_to_next_note, status, score);
            break;
        } else {
            shape = gregoriotex_determine_glyph_name(glyph, &type, &gtype);
            fprintf(f, "\\GreGlyph{%s}{%d}{%s}{%d}", code_point(shape,
                        glyph->u.notes.is_cavum, cpbuf, sizeof cpbuf),
                    pitch_value(glyph->u.notes.first_note->u.note.pitch),
                    next_custos(next_note_pitch, next_note_alteration, status),
                    type);
            write_signs(f, gtype, glyph, glyph->u.notes.first_note,
                    fuse_to_next_note, status, score);
            break;
        }
    }
}

static __inline unsigned int glyph_note_units(const gregorio_glyph *glyph)
{
    unsigned int count = 0;
    const gregorio_note *note;
    if (glyph->u.notes.glyph_type != G_ALTERATION) {
        for (note = glyph->u.notes.first_note; note; note = note->next) {
            ++count;
        }
    }
    return count;
}

/* here we absolutely need to pass the syllable as an argument, because we
 * will need the next note, that may be contained in the next syllable */

static unsigned int write_element(FILE *const f,
        const gregorio_syllable *const syllable,
        const gregorio_element *const element,
        gregoriotex_status *const status,
        const gregorio_score *const score)
{
    unsigned int note_unit_count = 0;
    if (element->type == GRE_ELEMENT) {
        gregorio_glyph *glyph;
        for (glyph = element->u.first_glyph; glyph; glyph = glyph->next) {
            switch (glyph->type) {
            case GRE_SPACE:
                switch (glyph->u.misc.unpitched.info.space) {
                case SP_ZERO_WIDTH:
                    fprintf(f, "\\GreEndOfGlyph{1}%%\n");
                    break;
                case SP_HALF_SPACE:
                    fprintf(f, "\\GreEndOfGlyph{22}%%\n");
                    break;
                case SP_INTERGLYPH_SPACE:
                    fprintf(f, "\\GreEndOfGlyph{0}%%\n");
                    break;
                default:
                    /* not reachable unless there's a programming error */
                    /* LCOV_EXCL_START */
                    gregorio_fail(write_element,
                            "encountered an unexpected glyph-level space");
                    break;
                    /* LCOV_EXCL_STOP */
                }
                break;

            case GRE_TEXVERB_GLYPH:
                if (glyph->texverb) {
                    fprintf(f, "%% verbatim text at glyph level:\n%s%%\n"
                            "%% end of verbatim text\n",
                            gregorio_texverb(glyph->texverb));
                }
                break;

            default:
                /* at this point glyph->type is GRE_GLYPH */
                assert(glyph->type == GRE_GLYPH);
                write_glyph(f, syllable, element, glyph, status, score);
                note_unit_count += glyph_note_units(glyph);
                if (glyph->next && glyph->next->type == GRE_GLYPH &&
                        glyph->next->u.notes.glyph_type != G_ALTERATION) {
                    if (is_fused(glyph->next->u.notes.liquescentia)) {
                        int space_case =
                            get_punctum_inclinatum_to_nobar_space_case(glyph);
                        if (space_case >= 0) {
                            /* fuse from punctum inclinatum to nobar glyph */
                            fprintf(f, "\\GreEndOfGlyph{%d}%%\n", space_case);
                        } else {
                            fprintf(f, "\\GreEndOfGlyph{1}%%\n");
                        }
                    } else if (is_puncta_inclinata(
                                glyph->next->u.notes.glyph_type)
                            || glyph->next->u.notes.glyph_type
                            == G_PUNCTA_INCLINATA) {
                        if ((is_puncta_inclinata(glyph->u.notes.glyph_type)
                                    || glyph->u.notes.glyph_type
                                    == G_PUNCTA_INCLINATA)
                                && glyph->next->u.notes.first_note->u.note.pitch
                                == gregorio_glyph_last_note(glyph)->u.note.pitch) {
                            /* special case for unison puncta inclinata */
                            fprintf(f, "\\GreEndOfGlyph{23}%%\n");
                        } else {
                            fprintf(f, "\\GreEndOfGlyph{9}%%\n");
                        }
                    } else if (glyph->u.notes.glyph_type != G_ALTERATION
                            || !glyph->next) {
                        fprintf(f, "\\GreEndOfGlyph{0}%%\n");
                    }
                }
                break;
            }
        }
    }
    return note_unit_count;
}

static void write_fixed_text_styles(FILE *f, gregorio_character *syllable_text,
        gregorio_character *next_syllable_text)
{
    if (syllable_text) {
        gregoriotex_ignore_style = gregoriotex_fix_style(syllable_text);
        if (gregoriotex_ignore_style) {
            fprintf(f, "\\GreSetFixedTextFormat{%d}",
                    gregoriotex_internal_style_to_gregoriotex
                    (gregoriotex_ignore_style));
        }
    }
    if (next_syllable_text) {
        gregoriotex_next_ignore_style = gregoriotex_fix_style(
                next_syllable_text);
        if (gregoriotex_next_ignore_style) {
            fprintf(f, "\\GreSetFixedNextTextFormat{%d}",
                    gregoriotex_internal_style_to_gregoriotex
                    (gregoriotex_next_ignore_style));
        }
    }
}

static void write_text(FILE *const f, const gregorio_character *const text)
{
    if (text == NULL) {
        fprintf(f, "{}{}{}{}{}");
        return;
    }
    fprintf(f, "{");
    gregorio_write_text(WTP_NORMAL, text, f, &gtex_write_verb,
            &gtex_print_char, &gtex_write_begin, &gtex_write_end,
            &gtex_write_special_char);
    fprintf(f, "}{");
    gregorio_write_first_letter_alignment_text(WTP_NORMAL, text,
            f, &gtex_write_verb, &gtex_print_char, &gtex_write_begin,
            &gtex_write_end, &gtex_write_special_char);
    gregoriotex_ignore_style = gregoriotex_next_ignore_style;
    gregoriotex_next_ignore_style = ST_NO_STYLE;
    fprintf(f, "}");
}

/*
 * Function printing the line clef change (only updating \localleftbox, not
 * printing the key). Useful for \GreDiscretionary.
 * TODO: I'm not sure about the third argument, but that's how it's called in
 * \GreChangeClef.
 */
static void gregoriotex_print_change_line_clef(FILE *f,
        const gregorio_element *const current_element)
{
    if (current_element->type == GRE_CLEF) {
        /* the third argument is 0 or 1 according to the need for a space
         * before the clef */
        fprintf(f, "\\GreSetLinesClef{%c}{%d}{1}{%d}{%c}{%d}{%d}%%\n",
                gregorio_clef_to_char(current_element->u.misc.clef.clef),
                current_element->u.misc.clef.line,
                clef_flat_height(current_element->u.misc.clef.clef,
                        current_element->u.misc.clef.line,
                        current_element->u.misc.clef.flatted),
                gregorio_clef_to_char(
                        current_element->u.misc.clef.secondary_clef),
                current_element->u.misc.clef.secondary_line,
                clef_flat_height(current_element->u.misc.clef.secondary_clef,
                        current_element->u.misc.clef.secondary_line,
                        current_element->u.misc.clef.secondary_flatted));
    }
}

static __inline bool next_is_bar(const gregorio_syllable *syllable,
        const gregorio_element *element)
{
    bool got_custos = false;
    if (element) {
        element = element->next;
    }

    while (syllable) {
        if (element) {
            if (element->type == GRE_BAR) {
                return true;
            }
            /* allow no more than one manual custos before a bar */
            if (got_custos || !is_manual_custos(element)) {
                return false;
            }
            got_custos = true;
            if (element->next) {
                /* look at the next element */
                element = element->next;
                continue;
            }
        }

        syllable = syllable->next_syllable;
        if (!syllable) {
            return false;
        }

        element = syllable->elements[0];
    }

    /* not reachable unless there's a programming error */
    /* LCOV_EXCL_START */
    gregorio_fail(next_is_bar, "unexpected end of syllables/elements");
    return false;
    /* LCOV_EXCL_STOP */
}

static void finish_syllable(FILE *f, gregorio_syllable *syllable) {
    /* Very last, if the syllable is the end of a no-linebreak area: */
    if (syllable->no_linebreak_area == NLBA_END) {
        fprintf(f, "\\GreEndNLBArea{%d}{0}%%\n",
                next_is_bar(syllable, NULL)? 3 : 1);
    }
    if (syllable->euouae == EUOUAE_END) {
        fprintf(f, "\\GreEndEUOUAE{%d}%%\n",
                next_is_bar(syllable, NULL)? 3 : 1);
    }
}

static void handle_final_bar(FILE *f, const char *type, gregorio_syllable *syllable)
{
    gregorio_element *element;
    fprintf(f, "\\GreFinal%s{%%\n", type);
    /* first element will be the bar, which we just handled, so skip it */
    for (element = (*syllable->elements)->next; element;
            element = element->next) {
        switch (element->type) {
        case GRE_TEXVERB_ELEMENT:
            if (element->texverb) {
                fprintf(f, "%% verbatim text at element level:\n%s%%\n"
                        "%% end of verbatim text\n",
                        gregorio_texverb(element->texverb));
            }
            break;

        case GRE_CUSTOS:
            assert(element->u.misc.pitched.force_pitch);
            fprintf(f, "\\GreFinalCustos{%d}{}%%\n",
                    pitch_value(element->u.misc.pitched.pitch));
            break;

        case GRE_END_OF_LINE:
            fprintf(f, "\\GreFinalNewLine%%\n");
            break;

        default:
            /* do nothing */
            break;
        }
    }
    fprintf(f, "}%%\n");
    finish_syllable(f, syllable);
}

static __inline void write_syllable_point_and_click(FILE *const f,
        const gregorio_syllable *const syllable,
        const gregoriotex_status *const status)
{
    if (status->point_and_click && syllable->src_line) {
        fprintf(f, "%u:%u:%u", syllable->src_line, syllable->src_offset,
                syllable->src_column + 1);
    }
}

static void write_syllable_text(FILE *f, const char *const syllable_type,
        const gregorio_syllable *const syllable,
        const bool ignored __attribute__((unused)))
{
    if (syllable_type != NULL) {
        fprintf(f, "%s{%s%s\\GreSetThisSyllable", syllable_type,
                syllable->clear? "\\GreClearSyllableText" : "",
                syllable->forced_center? "\\GreGABCForceCenters" : "");
        write_text(f, syllable->text);
        fprintf(f, "}");
    }
}

static void write_first_syllable_text(FILE *f, const char *const syllable_type,
        const gregorio_syllable *const syllable,
        const bool end_of_word)
{
    const gregorio_character *const text = syllable->text;
    gregorio_not_null(syllable_type, write_first_syllable_text, return);
    if (text == NULL) {
        fprintf(f, "}{%s}{\\GreSetNoFirstSyllableText}", syllable_type);
    } else {
        gregorio_character *text_with_initial = gregorio_clone_characters(text),
                *text_without_initial = gregorio_clone_characters(text);
        const gregorio_character *t;

        /* find out if there is a forced center -> has_forced_center */
        gregorio_center_determination center = syllable->forced_center?
                CENTER_FULLY_DETERMINED : CENTER_NOT_DETERMINED;

        gregorio_rebuild_first_syllable(&text_with_initial, false);
        gregorio_rebuild_characters(&text_with_initial, center, false);
        gregorio_set_first_word(&text_with_initial);

        gregorio_rebuild_first_syllable(&text_without_initial, true);
        gregorio_rebuild_characters(&text_without_initial, center, true);
        gregorio_set_first_word(&text_without_initial);

        fprintf(f, "}{%s}{%s%s\\GreSetFirstSyllableText", syllable_type,
                syllable->clear? "\\GreClearSyllableText" : "",
                syllable->forced_center? "\\GreGABCForceCenters" : "");

        fprintf(f, "{");
        gregorio_write_first_letter_alignment_text(WTP_FIRST_SYLLABLE,
                text_with_initial, f, &gtex_write_verb, &gtex_print_char,
                &gtex_write_begin, &gtex_write_end, &gtex_write_special_char);
        fprintf(f, "}{{");
        gregorio_write_text(WTP_FIRST_SYLLABLE, text_without_initial, f,
                &gtex_write_verb, &gtex_print_char, &gtex_write_begin,
                &gtex_write_end, &gtex_write_special_char);
        fprintf(f, "}}{{");
        gregorio_write_text(WTP_NORMAL, text_with_initial, f, &gtex_write_verb,
                &gtex_print_char, &gtex_write_begin, &gtex_write_end,
                &gtex_write_special_char);
        gregoriotex_ignore_style = gregoriotex_next_ignore_style;
        gregoriotex_next_ignore_style = ST_NO_STYLE;
        fprintf(f, "}}");

        /* Check to see if we need to force a hyphen (empty first syllable) */
        for (t = text_without_initial; t; t = t->next_character) {
            if (t->is_character) {
                break;
            } else if (t->cos.s.type == ST_T_BEGIN) {
                if (t->cos.s.style == ST_VERBATIM ||
                        t->cos.s.style == ST_SPECIAL_CHAR) {
                    break;
                } else if (t->cos.s.style == ST_INITIAL) {
                    for (; t; t = t->next_character) {
                        if (!t->is_character && t->cos.s.type == ST_T_END
                                && t->cos.s.style == ST_INITIAL) {
                            break;
                        }
                    }
                    if (!t) break;
                }
            }
        }
        if (t || end_of_word) {
            fprintf(f, "{}");
        } else {
            fprintf(f, "{\\GreEmptyFirstSyllableHyphen}");
        }

        fprintf(f, "}");

        gregorio_free_characters(text_with_initial);
        gregorio_free_characters(text_without_initial);
    }
}

static __inline void scan_syllable_for_eol(
        const gregorio_syllable *const syllable, char *const eol_forces_custos)
{
    const gregorio_element *element;
    if (syllable->elements) {
        for (element = *(syllable->elements); element; element = element->next) {
            if (element->type == GRE_END_OF_LINE) {
                if (element->u.misc.unpitched.info.eol_forces_custos) {
                    *eol_forces_custos = element->u.misc.unpitched.info
                            .eol_forces_custos_on?  '1' : '0';
                }
            }
        }
    }
}

/*
 * euouae_follows will be
 *  - '\0' if no euouae follows
 *  - '0' if euouae follows with no intervening linebreak
 *  - '1' if euouae follows with an intervening linebreak
 *
 * eol_forces_custos will be
 *  - '\0' if no linebreak follows or doesn't force a custos
 *  - '0' if a linebreak follows and forces custos off
 *  - '1' if a linebreak follows and forces custos on
 */
static __inline void anticipate_event(gregorio_syllable *syllable,
        char *const euouae_follows, char *const eol_forces_custos,
        unsigned short *const next_euouae_id)
{
    bool has_intervening_linebreak = false;

    *euouae_follows = '\0';
    *eol_forces_custos = '\0';
    *next_euouae_id = 0;

    if (syllable->next_syllable) {
        for (syllable = syllable->next_syllable;
                syllable && syllable->elements && *(syllable->elements)
                && (*(syllable->elements))->type == GRE_END_OF_LINE;
                syllable = syllable->next_syllable) {
            has_intervening_linebreak = true;
            /* we are at an end-of-line, so check if custos is forced */
            scan_syllable_for_eol(syllable, eol_forces_custos);
        }
        if (syllable) {
            scan_syllable_for_eol(syllable, eol_forces_custos);

            if (syllable->euouae == EUOUAE_BEGINNING) {
                *next_euouae_id = syllable->euouae_id = ++tex_position_id;
                *euouae_follows = has_intervening_linebreak? '1' : '0';
            }
        }
    }
}

static __inline void write_anticipated_event(FILE *f, const char euouae_follows,
        const char eol_forces_custos, const short next_euouae_id)
{
    if (euouae_follows) {
        fprintf(f, "%%\n\\GreNextSyllableBeginsEUOUAE{%hu}{%c}%%\n",
                next_euouae_id, euouae_follows);
    }
    if (eol_forces_custos) {
        fprintf(f, "%%\n\\GreUpcomingNewLineForcesCustos{%c}%%\n",
                eol_forces_custos);
    }
}

static __inline unsigned int count_note_units(const gregorio_element *element)
{
    unsigned int count = 0;
    for (; element; element = element->next) {
        if (element->type == GRE_ELEMENT) {
            const gregorio_glyph *glyph;
            for (glyph = element->u.first_glyph; glyph; glyph = glyph->next) {
                if (glyph->type == GRE_GLYPH) {
                    count += glyph_note_units(glyph);
                }
            }
        }
    }
    return count;
}

static __inline void handle_last_of_voice(FILE *const f,
        const gregorio_syllable *syllable,
        const gregorio_element *const element,
        const gregorio_element *const last_of_voice)
{
    if (element == last_of_voice) {
        if (syllable->next_syllable) {
            /* check for no-element syllables that follow */
            for (syllable = syllable->next_syllable;
                    syllable && (!syllable->elements || !*(syllable->elements));
                    syllable = syllable->next_syllable) {
                /* just loop */
            }
            /* if syllable is NULL here, then all syllables that follow
             * have no elements */
        }
        /* emit GreLastOfScore if we are either on the last syllable (and
         * thus the loop above is not executed, leaving syllable at the
         * current syllable) or if a syllable which follows the current
         * syllable has an element of some sort (and thus the loop above
         * stopped before running out of syllables); in any case, the check
         * is that syllable, at this point, is not NULL */
        if (syllable) {
            fprintf(f, "\\GreLastOfScore");
        }
    }
}

static bool is_before_linebreak(const gregorio_syllable *syllable,
        const gregorio_element *element)
{
    if (element) {
        element = element->next;
    }

    while (syllable) {
        if (element) {
            if (element->type == GRE_END_OF_LINE) {
                return true;
            }
            break;
        }

        syllable = syllable->next_syllable;
        if (syllable) {
            element = syllable->elements[0];
        }
    }

    return false;
}

/*
 * Arguments are relatively obvious. The most obscure is certainly first_of_disc
 * which is 0 all the time, except in the case of a "clef change syllable". In
 * this case we make a \GreDiscretionary with two arguments:
 *   1.what should be printed if the syllable is the last of its line (which
 *   basically means everything but clefs and custos), and
 *   2. what should be printed if it's in a middle of a line (which means
 *   everything)
 * So the first_of_disc argument is:
 *   0 if we don't know (general case)
 *   1 in case of the first argument of a \GreDiscretionary
 *   2 if we are in the second argument (necessary in order to avoid infinite loops)
 */
static void write_syllable(FILE *f, gregorio_syllable *syllable,
        unsigned char first_of_disc, gregoriotex_status *const status,
        const gregorio_score *const score,
        const gregorio_element *const *const last_of_voice,
        void (*const write_this_syllable_text)
        (FILE *, const char *, const gregorio_syllable *, bool))
{
    const gregorio_element *clef_change_element = NULL, *element;
    const char *syllable_type = NULL;
    bool anticipated_event_written = false;
    bool end_of_word;
    bool end_of_line;
    char euouae_follows;
    char eol_forces_custos;
    unsigned short next_euouae_id;
    unsigned int note_unit_count;
    gtex_alignment alignment = AT_ONE_NOTE;
    gtex_alteration alteration = ALT_NONE;

    gregorio_not_null(syllable, write_syllable, return);
    end_of_word = syllable->position == WORD_END
            || syllable->position == WORD_ONE_SYLLABLE || !syllable->text
            || !syllable->next_syllable;
    /* Very first: before anything, if the syllable is the beginning of a
     * no-linebreak area: */
    if (syllable->no_linebreak_area == NLBA_BEGINNING) {
        fprintf(f, "\\GreBeginNLBArea{1}{0}%%\n");
    }
    if (syllable->euouae == EUOUAE_BEGINNING) {
        fprintf(f, "\\GreBeginEUOUAE{%hu}%%\n", syllable->euouae_id);
    }
    if (syllable->elements && *(syllable->elements)) {
        /*
         * first we check if the syllable is only a end of line. If it is the
         * case, we don't print anything but a comment (to be able to read it
         * if we read GregorioTeX). The end of lines are treated separately in
         * GregorioTeX, it is buit inside the TeX structure.
         */
        if ((syllable->elements)[0]->type == GRE_END_OF_LINE) {
            gregorio_assert(syllable != score->first_syllable, write_syllable,
                    "line break is not supported on the first syllable",
                    return);
            if ((syllable->elements)[0]->u.misc.unpitched.info.eol_ragged) {
                fprintf(f, "%%\n%%\n\\GreNewParLine %%\n%%\n%%\n");
            } else {
                fprintf(f, "%%\n%%\n\\GreNewLine %%\n%%\n%%\n");
            }
            write_this_syllable_text(f, NULL, syllable, end_of_word);
            return;
        }
        /*
         * This case is not simple: if the syllable contains a clef change,
         * whether it is (c4) or (::c4) or (z0::c4), we put it in a
         * discretionary. Warning: only these three cases will have the expected
         * effect. So first we detect it:
         */
        if (first_of_disc == 0) {   /* to avoid infinite loops */
            clef_change_element = gregorio_get_clef_change(syllable);
            if (clef_change_element) {
                gregorio_assert(syllable != score->first_syllable,
                        write_syllable,
                        "clef change is not supported on the first syllable",
                        return);
                /*
                 * In this case, the first thing to do is to change the line clef
                 */
                gregoriotex_print_change_line_clef(f, clef_change_element);
                fprintf(f, "\\GreDiscretionary{0}{%%\n");
                write_syllable(f, syllable, 1, status, score, last_of_voice,
                        write_syllable_text);
                fprintf(f, "}{%%\n");
                write_syllable(f, syllable, 2, status, score, last_of_voice,
                        write_syllable_text);
                fprintf(f, "}%%\n");
                write_this_syllable_text(f, NULL, syllable, end_of_word);
                return;
            }
        }
        write_fixed_text_styles(f, syllable->text,
                syllable->next_syllable? syllable->next_syllable->text : NULL);
        if ((syllable->elements)[0]->type == GRE_BAR) {
            if (syllable != score->first_syllable) {
                if (!syllable->next_syllable && !syllable->text
                        && (syllable->elements)[0]->u.misc.unpitched.info.bar
                        == B_DIVISIO_FINALIS) {
                    handle_final_bar(f, "DivisioFinalis", syllable);
                    write_this_syllable_text(f, NULL, syllable, end_of_word);
                    return;
                }
                if (!syllable->next_syllable && !syllable->text
                        && (syllable->elements)[0]->u.misc.unpitched.info.bar
                        == B_DIVISIO_MAIOR) {
                    handle_final_bar(f, "DivisioMaior", syllable);
                    write_this_syllable_text(f, NULL, syllable, end_of_word);
                    return;
                }
            }
            /* the special case of first syllable will be treated as a normal
             * bar syllable */
            syllable_type = "\\GreBarSyllable";
        } else {
            if (first_of_disc != 0) {
                syllable_type = "\\GreBarSyllable";
            } else {
                syllable_type = "\\GreSyllable";
            }
        }
    } else {
        write_fixed_text_styles(f, syllable->text,
                syllable->next_syllable? syllable->next_syllable->text : NULL);
        syllable_type = "\\GreNoNoteSyllable";
    }
    write_this_syllable_text(f, syllable_type, syllable, end_of_word);
    fprintf(f, "{}{\\Gre%s}", syllable->first_word ? "FirstWord" : "Unstyled");
    if (end_of_word) {
        fprintf(f, "{1}");
    } else {
        fprintf(f, "{0}");
    }
    end_of_line = is_last_of_line(syllable);
    anticipate_event(syllable, &euouae_follows, &eol_forces_custos,
            &next_euouae_id);
    if (syllable->next_syllable) {
        fprintf(f, "{%s\\GreSetNextSyllable",
                syllable->next_syllable->forced_center?
                "\\GreGABCNextForceCenters" : "");
        write_text(f, syllable->next_syllable->text);
        if (end_of_line || first_of_disc == 1) {
            fprintf(f, "\\GreLastOfLine");
        } else if (euouae_follows) {
            fprintf(f, "\\GreLastSyllableBeforeEUOUAE{%hu}{%c}",
                    next_euouae_id, euouae_follows);
        }
        fprintf(f, "}{");
        write_syllable_point_and_click(f, syllable, status);
        syllable_first_type(syllable->next_syllable, &alignment, &alteration);
        fprintf(f, "}{{%d}{%d}}{", alignment, alteration);
    } else {
        fprintf(f, "{\\GreSetNextSyllable{}{}{}{}{}");
        if (end_of_line || first_of_disc == 1) {
            fprintf(f, "\\GreLastOfLine");
        }
        fprintf(f, "}{");
        write_syllable_point_and_click(f, syllable, status);
        fprintf(f, "}{{%d}{%d}}{", AT_EMPTY_SYLLABLE, ALT_NONE);
    }
    if (syllable->translation) {
        if (syllable->translation_type == TR_WITH_CENTER_BEGINNING) {
            fprintf(f, "%%\n\\GreWriteTranslationWithCenterBeginning{");
        } else {
            fprintf(f, "%%\n\\GreWriteTranslation{");
        }
        write_translation(f, syllable->translation);
        fprintf(f, "}%%\n");
    }
    if (syllable->translation_type) {
        if (syllable->translation_type == TR_WITH_CENTER_END)
            fprintf(f, "%%\n\\GreTranslationCenterEnd %%\n");
    }
    if (syllable->abovelinestext) {
        fprintf(f, "%%\n\\GreSetTextAboveLines{%s}%%\n",
                syllable->abovelinestext);
    }
    fprintf(f, "}{%%\n");

    fprintf(f, "\\GreSyllableNoteCount{%u}%%\n", syllable->elements?
            count_note_units(*syllable->elements) : 0);

    note_unit_count = 0;
    if (syllable->elements) {
        for (element = *syllable->elements; element; element = element->next) {
            if (element->nabc_lines && element->nabc) {
                signed char high_pitch = UNDETERMINED_HEIGHT;
                signed char low_pitch = UNDETERMINED_HEIGHT;
                size_t i;
                compute_element_height_extrema(element, &high_pitch,
                        &low_pitch);
                fixup_height_extrema(&high_pitch, &low_pitch);
                for (i = 0; i < element->nabc_lines; i++) {
                    if (element->nabc[i]) {
                        fprintf(f, "\\GreNABCNeumes{%d}{", (int)(i+1));
                        tex_escape_text(f, element->nabc[i]);
                        fprintf(f, "}{%d}{%d}%%\n", pitch_value(high_pitch),
                                pitch_value(low_pitch));
                    }
                }
            }
            switch (element->type) {
            case GRE_SPACE:
                switch (element->u.misc.unpitched.info.space) {
                case SP_LARGER_SPACE:
                    fprintf(f, "\\GreEndOfElement{1}{0}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_GLYPH_SPACE:
                    fprintf(f, "\\GreEndOfElement{2}{0}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_NEUMATIC_CUT:
                    fprintf(f, "\\GreEndOfElement{0}{0}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_AD_HOC_SPACE:
                    fprintf(f, "\\GreAdHocSpaceEndOfElement{%s}{0}{%u}%%\n",
                            element->u.misc.unpitched.info.ad_hoc_space_factor,
                            note_unit_count);
                    break;
                case SP_GLYPH_SPACE_NB:
                    fprintf(f, "\\GreEndOfElement{2}{1}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_LARGER_SPACE_NB:
                    fprintf(f, "\\GreEndOfElement{1}{1}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_NEUMATIC_CUT_NB:
                    fprintf(f, "\\GreEndOfElement{0}{1}{%u}%%\n",
                            note_unit_count);
                    break;
                case SP_AD_HOC_SPACE_NB:
                    fprintf(f, "\\GreAdHocSpaceEndOfElement{%s}{1}{%u}%%\n",
                            element->u.misc.unpitched.info.ad_hoc_space_factor,
                            note_unit_count);
                    break;
                default:
                    /* not reachable unless there's a programming error */
                    /* LCOV_EXCL_START */
                    gregorio_fail(write_syllable,
                            "encountered an unexpected element-level space");
                    break;
                    /* LCOV_EXCL_STOP */
                }
                break;

            case GRE_TEXVERB_ELEMENT:
                if (element->texverb) {
                    fprintf(f, "%% verbatim text at element level:\n%s%%\n"
                            "%% end of verbatim text\n",
                            gregorio_texverb(element->texverb));
                }
                break;

            case GRE_NLBA:
                if (element->u.misc.unpitched.info.nlba == NLBA_BEGINNING) {
                    fprintf(f, "\\GreBeginNLBArea{0}{0}%%\n");
                } else {
                    fprintf(f, "\\GreEndNLBArea{%d}{0}%%\n",
                            next_is_bar(syllable, element)? 3 : 0);
                }
                break;

            case GRE_ALT:
                if (element->texverb) {
                    fprintf(f, "\\GreSetTextAboveLines{%s}%%\n",
                            gregorio_texverb(element->texverb));
                }
                break;

            case GRE_CLEF:
                /* We don't print clef changes at the end of a line */
                if (first_of_disc != 1) {
                    if (is_before_linebreak(syllable, element)) {
                        signed char next_note_pitch;
                        gregorio_shape next_note_alteration;

                        next_note_pitch = gregorio_adjust_pitch_into_staff(
                                score, gregorio_determine_next_pitch(
                                syllable, element, NULL, &next_note_alteration)
                                - element->u.misc.clef.pitch_difference);

                        fputs(next_custos(next_note_pitch, next_note_alteration,
                                status), f);
                        gregoriotex_print_change_line_clef(f, element);
                    } else {
                        /* the third argument is 0 or 1 according to the need
                         * for a space before the clef */
                        fprintf(f, "\\GreChangeClef{%c}{%d}{%c}{%d}{%c}{%d}{%d}%%\n",
                                gregorio_clef_to_char(element->u.misc.clef.clef),
                                element->u.misc.clef.line,
                                (!element->previous || element->previous->type
                                 == GRE_BAR)? '0' : '1',
                                clef_flat_height(element->u.misc.clef.clef,
                                        element->u.misc.clef.line,
                                        element->u.misc.clef.flatted),
                                gregorio_clef_to_char(
                                        element->u.misc.clef.secondary_clef),
                                element->u.misc.clef.secondary_line,
                                clef_flat_height(
                                        element->u.misc.clef.secondary_clef,
                                        element->u.misc.clef.secondary_line,
                                        element->u.misc.clef.secondary_flatted));
                    }
                }
                break;

            case GRE_CUSTOS:
                if (first_of_disc != 1) {
                    signed char next_note_pitch;
                    gregorio_shape next_note_alteration;
                    const char *alteration = "";
                    /* We don't print custos before a bar at the end of a line.
                     * We also print an unbreakable larger space before the
                     * custos */
                    handle_last_of_voice(f, syllable, element, *last_of_voice);
                    next_note_pitch = gregorio_determine_next_pitch(syllable,
                            element, NULL, &next_note_alteration);
                    if (!element->u.misc.pitched.force_pitch) {
                        alteration = alteration_name(next_note_alteration);
                    }
                    fprintf(f, "\\GreCustos{%d}{%s}%s%%\n",
                            pitch_value(element->u.misc.pitched.pitch), alteration,
                            next_custos(next_note_pitch, next_note_alteration,
                            status));
                    ++note_unit_count;
                }
                break;

            case GRE_SUPPRESS_CUSTOS:
                handle_last_of_voice(f, syllable, element, *last_of_voice);
                fprintf(f, "\\GreSuppressEolCustos %%\n");
                status->suppressed_custos = true;
                break;

            case GRE_BAR:
                handle_last_of_voice(f, syllable, element, *last_of_voice);
                write_bar(f, score, syllable, element, first_of_disc);
                break;

            case GRE_END_OF_LINE:
                if (!element->next) {
                    write_anticipated_event(f, euouae_follows,
                            eol_forces_custos, next_euouae_id);
                    anticipated_event_written = true;
                }
                /* here we suppose we don't have two linebreaks in the same
                 * syllable */
                if (element->u.misc.unpitched.info.eol_ragged) {
                    fprintf(f, "%%\n%%\n\\GreNewParLine %%\n%%\n%%\n");
                } else {
                    fprintf(f, "%%\n%%\n\\GreNewLine %%\n%%\n%%\n");
                }
                break;

            default:
                /* here current_element->type is GRE_ELEMENT */
                assert(element->type == GRE_ELEMENT);
                handle_last_of_voice(f, syllable, element, *last_of_voice);
                note_unit_count += write_element(f, syllable, element, status,
                        score);
                if (element->next && (element->next->type == GRE_ELEMENT
                                || (element->next->next
                                        && element->next->type == GRE_ALT
                                        && element->next->next->type ==
                                        GRE_ELEMENT))) {
                    fprintf(f, "\\GreEndOfElement{0}{0}{%u}%%\n",
                            note_unit_count);
                }
                break;
            }
        }
    }
    if (!anticipated_event_written) {
        write_anticipated_event(f, euouae_follows, eol_forces_custos,
                next_euouae_id);
    }
    fprintf(f, "}%%\n");
    if (syllable->position == WORD_END
            || syllable->position == WORD_ONE_SYLLABLE || !syllable->text) {
        fprintf(f, "%%\n");
    }
    finish_syllable(f, syllable);
}

static char *digest_to_hex(const unsigned char digest[SHA1_DIGEST_SIZE])
{
    static const char *const hex = "0123456789abcdef";
    static char result[41];

    char *p = result;
    unsigned char byte;

    int i;
    for (i = 0; i < SHA1_DIGEST_SIZE; ++i) {
        byte = digest[i];

        *(p++) = hex[(byte >> 4) & 0x0FU];
        *(p++) = hex[byte & 0x0FU];
    }

    *p = '\0';

    return result;
}

static void initialize_score(gregoriotex_status *const status,
        gregorio_score *score, const bool point_and_click,
        const gregorio_element **const last_of_voice)
{
    gregorio_syllable *syllable;

    status->bottom_line = false;
    status->top_height = status->bottom_height = UNDETERMINED_HEIGHT;
    status->abovelinestext = status->translation = false;
    status->suppressed_custos = false;

    /* first pass to compute positioning */
    for (syllable = score->first_syllable; syllable;
            syllable = syllable->next_syllable) {
        int voice;

        for (voice = 0; voice < score->number_of_voices; ++voice) {
            gregoriotex_compute_positioning(syllable->elements[voice], score);
        }
    }

    gregoriotex_compute_cross_syllable_positioning(score);

    for (syllable = score->first_syllable; syllable;
            syllable = syllable->next_syllable) {
        int voice;

        if (syllable->translation) {
            status->translation = true;
        }

        if (syllable->abovelinestext) {
            status->abovelinestext = true;
        }

        /* simultaneously compute height extrema and determine the last "real"
         * element in each voice */
        for (voice = 0; voice < score->number_of_voices; ++voice) {
            gregorio_element *element;

            for (element = syllable->elements[voice]; element;
                    element = element->next) {
                gregorio_glyph *glyph;

                switch (element->type) {
                case GRE_ALT:
                    status->abovelinestext = true;
                    break;

                case GRE_CUSTOS:
                    last_of_voice[voice] = element;
                    break;

                case GRE_ELEMENT:
                    for (glyph = element->u.first_glyph; glyph;
                            glyph = glyph->next) {
                        if (glyph->type == GRE_GLYPH) {
                            last_of_voice[voice] = element;
                            compute_height_extrema(glyph,
                                    glyph->u.notes.first_note,
                                    &(status->top_height),
                                    &(status->bottom_height));
                        }
                    }
                    break;

                case GRE_BAR:
                    last_of_voice[voice] = element;
                    break;

                default:
                    /* to eliminate the warning */
                    break;
                }
            }
        }
    }

    fixup_height_extrema(&(status->top_height), &(status->bottom_height));

    status->point_and_click = point_and_click;
}

static void write_header(FILE *const f, const char *const name,
        const char *const value)
{
    if (value) {
        fprintf(f, "\\GreHeader{");
        tex_escape_text(f, name);
        fprintf(f, "}{");
        tex_escape_text(f, value);
        fprintf(f, "}%%\n");
    }
}

static void write_headers(FILE *const f, gregorio_score *const score)
{
    gregorio_header *header;

    fprintf(f, "\\GreBeginHeaders %%\n");
    for (header = score->headers; header; header = header->next) {
        write_header(f, header->name, header->value);
    }
    fprintf(f, "\\GreEndHeaders %%\n");
}

static void suppress_expansion(FILE *const f, const char *text)
{
    if (!text) {
        return;
    }

    for (; *text; ++text) {
        if (*text == '\\') {
            fprintf(f, "\\noexpand");
        }
        fputc(*text, f);
    }
}

static int first_note_near_clef(const gregorio_score *const score) {
    gregorio_clef_info clef = gregorio_default_clef;
    if (score->first_voice_info) {
        clef = score->first_voice_info->initial_clef;
        if (!clef.secondary_line && !clef.flatted && score->first_syllable
                && score->first_syllable->elements) {
            const gregorio_element *element = score->first_syllable->elements[0];
            if (element && element->type == GRE_ELEMENT) {
                const gregorio_glyph *glyph = element->u.first_glyph;
                if (glyph && glyph->type == GRE_GLYPH) {
                    const signed char clef_pitch = LOW_LINE_PITCH
                        + ((clef.line - 1) * 2);
                    const gregorio_note *low_note = glyph->u.notes.first_note;
                    const gregorio_note *high_note = low_note;
                    switch (glyph->u.notes.glyph_type) {
                    case G_PODATUS:
                        /* next note is above the previous */
                        if (low_note->next) {
                            high_note = low_note->next;
                        }
                        break;
                    case G_FLEXA:
                    case G_PORRECTUS:
                    case G_PORRECTUS_FLEXUS:
                        /* there is a stem the size of the ambitus */
                        if (high_note->next) {
                            low_note = high_note->next;
                        }
                        break;
                    default:
                        /* to prevent the enum warning */
                        break;
                    }
                    if (high_note->u.note.pitch < clef_pitch - 3
                            || low_note->u.note.pitch > clef_pitch + 3) {
                        return 0;
                    }
                }
            }
        }
    }
    return 1;
}

static int clef_size(const gregorio_clef_info *const clef)
{
    /* this is a heuristic clef size approximation:
     * C-clef = 1
     * F-clef = 2
     * flatted = +2
     * unstacked double-clef = +1 (plus the clef size)
     */
    /* purposely making line signed */
    int line_diff = clef->line - clef->secondary_line;
    int size;
    if (clef->clef == CLEF_F) {
        size = 2;
    } else {
        size = 1;
    }
    if (clef->flatted) {
        size += 2;
    }
    if (clef->secondary_line) {
        if (line_diff < -1 || line_diff > 1) { /* stacked */
            int secondary_size;
            if (clef->secondary_clef == CLEF_F) {
                secondary_size = 2;
            } else {
                secondary_size = 1;
            }
            if (clef->secondary_flatted) {
                secondary_size += 2;
            }
            if (secondary_size > size) {
                size = secondary_size;
            }
        } else { /* unstacked */
            size += 1;
            if (clef->secondary_clef == CLEF_F) {
                size += 2;
            } else {
                size += 1;
            }
            if (clef->secondary_flatted) {
                size += 2;
            }
        }
    }
    return size;
}

static void write_largest_clef(FILE *const f, gregorio_score *const score)
{
    const gregorio_syllable *syllable;
    const gregorio_element *element;
    gregorio_clef_info clef = gregorio_default_clef;
    int size;

    if (score->first_voice_info) {
        clef = score->first_voice_info->initial_clef;
    }
    size = clef_size(&clef);

    for (syllable = score->first_syllable; syllable;
            syllable = syllable->next_syllable) {
        if (syllable->elements) {
            for (element = *syllable->elements; element;
                    element = element->next) {
                if (element->type == GRE_CLEF) {
                    const int this_size = clef_size(&element->u.misc.clef);
                    if (this_size > size) {
                        clef = element->u.misc.clef;
                        size = this_size;
                    }
                }
            }
        }
    }

    fprintf(f, "\\GreSetLargestClef{%c}{%d}{%d}{%c}{%d}{%d}%%\n",
            gregorio_clef_to_char(clef.clef), clef.line,
            clef_flat_height(clef.clef, clef.line, clef.flatted),
            gregorio_clef_to_char(clef.secondary_clef), clef.secondary_line,
            clef_flat_height(clef.secondary_clef, clef.secondary_line,
                    clef.secondary_flatted));
}

void gregoriotex_write_score(FILE *const f, gregorio_score *const score,
        const char *const point_and_click_filename)
{
    gregorio_clef_info clef = gregorio_default_clef;
    gregorio_syllable *current_syllable;
    int annotation_num;
    gregoriotex_status status;
    const gregorio_element *last_of_voice[MAX_NUMBER_OF_VOICES];

    memset(last_of_voice, 0, sizeof last_of_voice);
    initialize_score(&status, score, point_and_click_filename != NULL,
            last_of_voice);

    gregorio_assert(f, gregoriotex_write_score, "call with NULL file", return);

    gregorio_assert_only(score->number_of_voices == 1, gregoriotex_write_score,
            "gregoriotex only works in monophony (for the moment)");

    fprintf(f, "%% File generated by gregorio %s\n", GREGORIO_VERSION);
    fprintf(f, "\\GregorioTeXAPIVersion{%s}%%\n", VERSION);

    if (score->name) {
        fprintf(f, "%% Name: %s\n", score->name);
    }
    if (score->author) {
        fprintf(f, "%% Author: %s\n", score->author);
    }
    if (score->gabc_copyright) {
        fprintf(f, "%% The copyright of this gabc is: %s\n",
                score->gabc_copyright);
    }
    if (score->score_copyright) {
        fprintf(f, "%% The copyright of the score is: %s\n",
                score->score_copyright);
    }

    write_headers(f, score);

    if (score->first_voice_info) {
        clef = score->first_voice_info->initial_clef;
    }
    fprintf(f, "\\GreBeginScore{%s}{%d}{%d}{%d}{%d}{%s}{%u}"
            "{\\GreInitialClefPosition{%d}{%d}}%%\n",
            digest_to_hex(score->digest), status.top_height,
            status.bottom_height, bool_to_int(status.translation),
            bool_to_int(status.abovelinestext),
            point_and_click_filename? point_and_click_filename : "",
            score->staff_lines, clef.line, clef.secondary_line);
    if (score->nabc_lines) {
        fprintf(f, "\\GreScoreNABCLines{%d}", (int)score->nabc_lines);
    }
    if (score->annotation[0]) {
        fprintf(f, "\\GreAnnotationLines");
        for (annotation_num = 0; annotation_num < MAX_ANNOTATIONS;
             ++annotation_num) {
            if (score->annotation[annotation_num]) {
                fprintf(f, "{%s}",
                        score->annotation[annotation_num]);
            }
            else {
                fprintf(f, "{}");
            }
        }
        fprintf(f, "%%\n");
    }
    if (score->mode) {
        fprintf(f, "\\GreMode{");
        if (*(score->mode) >= '1' && *(score->mode) <= '8') {
            fprintf(f, "\\GreModeNumber{%c}%s", *(score->mode), score->mode + 1);
        } else {
            fprintf(f, "%s", score->mode);
        }
        fprintf(f, "}{");
        suppress_expansion(f, score->mode_modifier);
        fprintf(f, "}{");
        suppress_expansion(f, score->mode_differentia);
        fprintf(f, "}%%\n");
    }

    write_largest_clef(f, score);
    fprintf(f, "\\GreScoreOpening{%%\n"); /* GreScoreOpening#1 */
    if (score->first_voice_info) {
        gregoriotex_write_voice_info(f, score->first_voice_info);
    }
    fprintf(f, "}{%%\n"); /* GreScoreOpening#2 */
    fprintf(f, "\\GreSetInitialClef{%c}{%d}{%d}{%c}{%d}{%d}{%d}%%\n",
            gregorio_clef_to_char(clef.clef), clef.line,
            clef_flat_height(clef.clef, clef.line, clef.flatted),
            gregorio_clef_to_char(clef.secondary_clef), clef.secondary_line,
            clef_flat_height(clef.secondary_clef, clef.secondary_line,
                    clef.secondary_flatted),
            first_note_near_clef(score));
    fprintf(f, "}{%%\n"); /* GreScoreOpening#3 */
    current_syllable = score->first_syllable;
    if (current_syllable) {
        write_syllable(f, current_syllable, 0, &status, score, last_of_voice,
                write_first_syllable_text);
        current_syllable = current_syllable->next_syllable;
    } else {
        /* edge case: a score with no syllables */
        fprintf(f, "}{}{\\GreSetNoFirstSyllableText}%%\n");
    }
    while (current_syllable) {
        write_syllable(f, current_syllable, 0, &status, score, last_of_voice,
                write_syllable_text);
        current_syllable = current_syllable->next_syllable;
    }
    fprintf(f, "\\GreEndScore %%\n\\endinput %%\n");
}