File: importmxmlpass2.cpp

package info (click to toggle)
musescore 2.3.2%2Bdfsg2-7~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 187,932 kB
  • sloc: cpp: 264,610; xml: 176,707; sh: 3,311; ansic: 1,384; python: 356; makefile: 188; perl: 82; pascal: 78
file content (5955 lines) | stat: -rw-r--r-- 232,921 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
//=============================================================================
//  MuseScore
//  Linux Music Score Editor
//
//  Copyright (C) 2015 Werner Schweer and others
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================

#include "libmscore/arpeggio.h"
#include "libmscore/accidental.h"
#include "libmscore/breath.h"
#include "libmscore/chord.h"
#include "libmscore/chordline.h"
#include "libmscore/chordlist.h"
#include "libmscore/chordrest.h"
#include "libmscore/drumset.h"
#include "libmscore/dynamic.h"
#include "libmscore/figuredbass.h"
#include "libmscore/fingering.h"
#include "libmscore/fret.h"
#include "libmscore/glissando.h"
#include "libmscore/hairpin.h"
#include "libmscore/harmony.h"
#include "libmscore/instrchange.h"
#include "libmscore/instrtemplate.h"
#include "libmscore/interval.h"
#include "libmscore/jump.h"
#include "libmscore/keysig.h"
#include "libmscore/lyrics.h"
#include "libmscore/marker.h"
#include "libmscore/measure.h"
#include "libmscore/mscore.h"
#include "libmscore/note.h"
#include "libmscore/part.h"
#include "libmscore/pedal.h"
#include "libmscore/rest.h"
#include "libmscore/slur.h"
#include "libmscore/staff.h"
#include "libmscore/stafftext.h"
#include "libmscore/sym.h"
#include "libmscore/tempotext.h"
#include "libmscore/tie.h"
#include "libmscore/timesig.h"
#include "libmscore/tremolo.h"
#include "libmscore/trill.h"
#include "libmscore/utils.h"
#include "libmscore/volta.h"

#include "importmxmllogger.h"
#include "importmxmlnoteduration.h"
#include "importmxmlnotepitch.h"
#include "importmxmlpass2.h"
#include "musicxmlfonthandler.h"
#include "musicxmlsupport.h"
#include "preferences.h"

namespace Ms {

//---------------------------------------------------------
//   local defines for debug output
//---------------------------------------------------------

//#define DEBUG_VOICE_MAPPER true

//---------------------------------------------------------
//   support enums / structs / classes
//---------------------------------------------------------

//---------------------------------------------------------
//   MusicXmlTupletDesc
//---------------------------------------------------------

MusicXmlTupletDesc::MusicXmlTupletDesc()
      : type(MxmlStartStop::NONE), placement(Element::Placement::BELOW),
      bracket(Tuplet::BracketType::AUTO_BRACKET), shownumber(Tuplet::NumberType::SHOW_NUMBER)
      {
      // nothing
      }

//---------------------------------------------------------
//   MusicXmlLyricsExtend
//---------------------------------------------------------

//---------------------------------------------------------
//   init
//---------------------------------------------------------

void MusicXmlLyricsExtend::init()
      {
      _lyrics.clear();
      }

//---------------------------------------------------------
//   addLyric
//---------------------------------------------------------

// add a single lyric to be extended later
// called when lyric with "extend" or "extend type=start" is found

void MusicXmlLyricsExtend::addLyric(Lyrics* const lyric)
      {
      _lyrics.insert(lyric);
      }

//---------------------------------------------------------
//   lastChordTicks
//---------------------------------------------------------

// find the duration of the chord starting at or after s in track and ending at tick

static int lastChordTicks(const Segment* s, const int track, const int tick)
      {
      while (s && s->tick() < tick) {
            Element* el = s->element(track);
            if (el && el->isChordRest()) {
                  ChordRest* cr = static_cast<ChordRest*>(el);
                  if (cr->tick() + cr->actualTicks() == tick)
                        return cr->actualTicks();
                  }
            s = s->nextCR(track, true);
            }
      return 0;
      }

//---------------------------------------------------------
//   setExtend
//---------------------------------------------------------

// set extend for lyric no in track to end at tick
// called when lyric (with or without "extend") or note with "extend type=stop" is found
// note that no == -1 means all lyrics in this track

void MusicXmlLyricsExtend::setExtend(const int no, const int track, const int tick)
      {
      QList<Lyrics*> list;
      foreach(Lyrics* l, _lyrics) {
            Element* const el = l->parent();
            if (el->type() == Element::Type::CHORD) {       // TODO: rest also possible ?
                  ChordRest* const par = static_cast<ChordRest*>(el);
                  if (par->track() == track && (no == -1 || l->no() == no)) {
                        int lct = lastChordTicks(l->segment(), track, tick);
                        if (lct > 0) {
                              // set lyric tick to the total length fron the lyric note
                              // plus all notes covered by the melisma minus the last note length
                              l->setTicks(tick - par->tick() - lct);
                              }
                        list.append(l);
                        }
                  }
            }
      // cleanup
      foreach(Lyrics* l, list) {
            _lyrics.remove(l);
            }
      }

//---------------------------------------------------------
//   MusicXMLStepAltOct2Pitch
//---------------------------------------------------------

/**
 Convert MusicXML \a step (0=C, 1=D, etc.) / \a alter / \a octave to midi pitch.
 Note: same code is in pass 1 and in pass 2.
 TODO: combine
 */

static int MusicXMLStepAltOct2Pitch(int step, int alter, int octave)
      {
      //                       c  d  e  f  g  a   b
      static int table[7]  = { 0, 2, 4, 5, 7, 9, 11 };
      if (step < 0 || step > 6) {
            qDebug("MusicXMLStepAltOct2Pitch: illegal step %d", step);
            return -1;
            }
      int pitch = table[step] + alter + (octave+1) * 12;

      if (pitch < 0)
            pitch = -1;
      if (pitch > 127)
            pitch = -1;

      return pitch;
      }

//---------------------------------------------------------
//   xmlSetPitch
//---------------------------------------------------------

/**
 Convert MusicXML \a step / \a alter / \a octave to midi pitch,
 set pitch and tpc.
 Note that n's staff and track have not been set yet
 */

static void xmlSetPitch(Note* n, int step, int alter, int octave, const int octaveShift, const Instrument* instr)
      {
      //qDebug("xmlSetPitch(n=%p, step=%d, alter=%d, octave=%d, octaveShift=%d)",
      //       n, step, alter, octave, octaveShift);

      //const Staff* staff = n->score()->staff(track / VOICES);
      //const Instrument* instr = staff->part()->instr();

      const Interval intval = instr->transpose();     // TODO: tick

      //qDebug("  staff=%p instr=%p dia=%d chro=%d",
      //       staff, instr, (int) intval.diatonic, (int) intval.chromatic);

      int pitch = MusicXMLStepAltOct2Pitch(step, alter, octave);
      pitch += intval.chromatic; // assume not in concert pitch
      pitch += 12 * octaveShift; // correct for octave shift
      // ensure sane values
      pitch = limit(pitch, 0, 127);

      int tpc2 = step2tpc(step, AccidentalVal(alter));
      int tpc1 = Ms::transposeTpc(tpc2, intval, true);
      n->setPitch(pitch, tpc1, tpc2);
      //qDebug("  pitch=%d tpc1=%d tpc2=%d", n->pitch(), n->tpc1(), n->tpc2());
      }

//---------------------------------------------------------
//   fillGap
//---------------------------------------------------------

/**
 Fill one gap (tstart - tend) in this track in this measure with rest(s).
 */

static void fillGap(Measure* measure, int track, int tstart, int tend)
      {
      int ctick = tstart;
      int restLen = tend - tstart;
      // qDebug("\nfillGIFV     fillGap(measure %p track %d tstart %d tend %d) restLen %d len",
      //        measure, track, tstart, tend, restLen);
      // note: as MScore::division (#ticks in a quarter note) equals 480
      // MScore::division / 64 (#ticks in a 256th note) uequals 7.5 but is rounded down to 7
      while (restLen > MScore::division / 64) {
            int len = restLen;
            TDuration d(TDuration::DurationType::V_INVALID);
            if (measure->ticks() == restLen)
                  d.setType(TDuration::DurationType::V_MEASURE);
            else
                  d.setVal(len);
            Rest* rest = new Rest(measure->score(), d);
            rest->setDuration(Fraction::fromTicks(len));
            rest->setTrack(track);
            rest->setVisible(false);
            Segment* s = measure->getSegment(rest, tstart);
            s->add(rest);
            len = rest->globalDuration().ticks();
            // qDebug(" %d", len);
            ctick   += len;
            restLen -= len;
            }
      }

//---------------------------------------------------------
//   fillGapsInFirstVoices
//---------------------------------------------------------

/**
 Fill gaps in first voice of every staff in this measure for this part with rest(s).
 */

static void fillGapsInFirstVoices(Measure* measure, Part* part)
      {
      Q_ASSERT(measure);
      Q_ASSERT(part);

      int measTick     = measure->tick();
      int measLen      = measure->ticks();
      int nextMeasTick = measTick + measLen;
      int staffIdx = part->score()->staffIdx(part);
      /*
       qDebug("fillGIFV measure %p part %p idx %d nstaves %d tick %d - %d (len %d)",
       measure, part, staffIdx, part->nstaves(),
       measTick, nextMeasTick, measLen);
       */
      for (int st = 0; st < part->nstaves(); ++st) {
            int track = (staffIdx + st) * VOICES;
            int endOfLastCR = measTick;
            for (Segment* s = measure->first(); s; s = s->next()) {
                  // qDebug("fillGIFV   segment %p tp %s", s, s->subTypeName());
                  Element* el = s->element(track);
                  if (el) {
                        // qDebug(" el[%d] %p", track, el);
                        if (s->isChordRest()) {
                              ChordRest* cr  = static_cast<ChordRest*>(el);
                              int crTick     = cr->tick();
                              int crLen      = cr->globalDuration().ticks();
                              int nextCrTick = crTick + crLen;
                              /*
                               qDebug(" chord/rest tick %d - %d (len %d)",
                               crTick, nextCrTick, crLen);
                               */
                              if (crTick > endOfLastCR) {
                                    /*
                                     qDebug(" GAP: track %d tick %d - %d",
                                     track, endOfLastCR, crTick);
                                     */
                                    fillGap(measure, track, endOfLastCR, crTick);
                                    }
                              endOfLastCR = nextCrTick;
                              }
                        }
                  }
            if (nextMeasTick > endOfLastCR) {
                  /*
                   qDebug("fillGIFV   measure end GAP: track %d tick %d - %d",
                   track, endOfLastCR, nextMeasTick);
                   */
                  fillGap(measure, track, endOfLastCR, nextMeasTick);
                  }
            }
      }

//---------------------------------------------------------
//   hasDrumset
//---------------------------------------------------------

/**
 Determine if \a mxmlDrumset contains a valid drumset.
 This is the case if any instrument has a midi-unpitched element,
 (which stored in the MusicXMLDrumInstrument pitch field).
 */

static bool hasDrumset(const MusicXMLDrumset& mxmlDrumset)
      {
      bool res = false;
      MusicXMLDrumsetIterator ii(mxmlDrumset);
      while (ii.hasNext()) {
            ii.next();
            // debug: dump the drumset
            //qDebug("hasDrumset: instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString()));
            int pitch = ii.value().pitch;
            if (0 <= pitch && pitch <= 127) {
                  res = true;
                  }
            }

      /*
      for (const auto& instr : mxmlDrumset) {
            // MusicXML elements instrument-name, midi-program, instrument-sound, virtual-library, virtual-name
            // in a shell script use "mscore ... 2>&1 | grep GREP_ME | cut -d' ' -f3-" to extract
            qDebug("GREP_ME '%s',%d,'%s','%s','%s'",
                   qPrintable(instr.name),
                   instr.midiProgram + 1,
                   qPrintable(instr.sound),
                   qPrintable(instr.virtLib),
                   qPrintable(instr.virtName)
                   );
            }
       */

      return res;
      }

//---------------------------------------------------------
//   initDrumset
//---------------------------------------------------------

/**
 Initialize drumset \a drumset.
 */

// determine if the part contains a drumset
// this is the case if any instrument has a midi-unpitched element,
// (which stored in the MusicXMLDrumInstrument pitch field)
// if the part contains a drumset, Drumset drumset is intialized

static void initDrumset(Drumset* drumset, const MusicXMLDrumset& mxmlDrumset)
      {
      drumset->clear();
      MusicXMLDrumsetIterator ii(mxmlDrumset);
      while (ii.hasNext()) {
            ii.next();
            // debug: also dump the drumset for this part
            //qDebug("initDrumset: instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString()));
            int pitch = ii.value().pitch;
            if (0 <= pitch && pitch <= 127) {
                  drumset->addDrumInstrument(ii.value().pitch, DrumInstrument(ii.value().name.toLatin1().constData(),
                                         ii.value().notehead, ii.value().line, ii.value().stemDirection));
                  }
            }
      }

//---------------------------------------------------------
//   createInstrument
//---------------------------------------------------------

/**
 Create an Instrument based on the information in \a mxmlInstr.
 */

static Instrument createInstrument(const MusicXMLDrumInstrument& mxmlInstr)
      {
      Instrument instr;

      InstrumentTemplate* it {};
      if (!mxmlInstr.sound.isEmpty()) {
            it = Ms::searchTemplateForMusicXmlId(mxmlInstr.sound);
            }

      /*
      qDebug("sound '%s' it %p trackname '%s' program %d",
             qPrintable(mxmlInstr.sound), it,
             it ? qPrintable(it->trackName) : "",
             mxmlInstr.midiProgram);
       */

      if (it) {
            // initialize from template with matching MusicXmlId
            instr = Instrument::fromTemplate(it);
            // reset transpose, as it is determined later from MusicXML data
            instr.setTranspose(Interval());
            }
      else {
            // set articulations to default (global articulations)
            instr.setArticulation(articulation);
            // set default program
            instr.channel(0)->program = mxmlInstr.midiProgram >= 0 ? mxmlInstr.midiProgram : 0;
            }

      // add / overrule with values read from MusicXML
      instr.channel(0)->pan = mxmlInstr.midiPan;
      instr.channel(0)->volume = mxmlInstr.midiVolume;
      instr.setTrackName(mxmlInstr.name);

      return instr;
      }

//---------------------------------------------------------
//   setFirstInstrument
//---------------------------------------------------------

/**
 Set first instrument for Part \a part
 */

static void setFirstInstrument(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
                               Part* part, const QString& partId,
                               const QString& instrId, const MusicXMLDrumset& mxmlDrumset)
      {
      if (mxmlDrumset.size() > 0) {
            //qDebug("setFirstInstrument: initial instrument '%s'", qPrintable(instrId));
            MusicXMLDrumInstrument mxmlInstr;
            if (instrId == "")
                  mxmlInstr = mxmlDrumset.first();
            else if (mxmlDrumset.contains(instrId))
                  mxmlInstr = mxmlDrumset.value(instrId);
            else {
                  logger->logError(QString("initial instrument '%1' not found in part '%2'")
                                   .arg(instrId).arg(partId), xmlreader);
                  mxmlInstr = mxmlDrumset.first();
                  }

            Instrument instr = createInstrument(mxmlInstr);
            part->setInstrument(instr);
            if (mxmlInstr.midiChannel >= 0) part->setMidiChannel(mxmlInstr.midiChannel);
            // note: setMidiProgram() does more than simply setting the MIDI program
            if (mxmlInstr.midiProgram >= 0) part->setMidiProgram(mxmlInstr.midiProgram);
            }
      else
            logger->logError(QString("no instrument found for part '%1'")
                             .arg(partId), xmlreader);
      }

//---------------------------------------------------------
//   setStaffTypePercussion
//---------------------------------------------------------

/**
 Set staff type to percussion
 */

static void setStaffTypePercussion(Part* part, Drumset* drumset)
      {
      for (int j = 0; j < part->nstaves(); ++j)
            if (part->staff(j)->lines() == 5 && !part->staff(j)->isDrumStaff())
                  part->staff(j)->setStaffType(StaffType::preset(StaffTypes::PERC_DEFAULT));
      // set drumset for instrument
      part->instrument()->setDrumset(drumset);
      part->instrument()->channel(0)->bank = 128;
      part->instrument()->channel(0)->updateInitList();
      }

//---------------------------------------------------------
//   findDeleteStaffText
//---------------------------------------------------------

/**
 Find a non-empty staff text in \a s at \a track (which originates as MusicXML <words>).
 If found, delete it and return its text.
 */

static QString findDeleteStaffText(Segment* s, int track)
      {
      //qDebug("findDeleteWords(s %p track %d)", s, track);
      foreach (Element* e, s->annotations()) {
            //qDebug("findDeleteWords e %p type %hhd track %d", e, e->type(), e->track());
            if (e->type() != Element::Type::STAFF_TEXT || e->track() < track || e->track() >= track+VOICES)
                  continue;
            Text* t = static_cast<Text*>(e);
            //qDebug("findDeleteWords t %p text '%s'", t, qPrintable(t->text()));
            QString res = t->xmlText();
            if (res != "") {
                  s->remove(t);
                  return res;
                  }
            }
      return "";
      }

//---------------------------------------------------------
//   setPartInstruments
//---------------------------------------------------------

static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
                               Part* part, const QString& partId,
                               Score* score, const MusicXmlInstrList& il, const MusicXMLDrumset& mxmlDrumset)
      {
      QString prevInstrId;
      for (auto it = il.cbegin(); it != il.cend(); ++it) {
            Fraction f = (*it).first;
            if (f == Fraction(0, 1))
                  prevInstrId = (*it).second;  // instrument id at t = 0
            else if (f > Fraction(0, 1)) {
                  auto instrId = (*it).second;
                  bool mustInsert = instrId != prevInstrId;
                  /*
                  qDebug("f %s previd %s id %s mustInsert %d",
                         qPrintable(f.print()),
                         qPrintable(prevInstrId),
                         qPrintable(instrId),
                         mustInsert);
                   */
                  if (mustInsert) {
                        const int staff = score->staffIdx(part);
                        const int track = staff * VOICES;
                        const int tick = f.ticks();
                        //qDebug("instrument change: tick %s (%d) track %d instr '%s'",
                        //       qPrintable(f.print()), f.ticks(), track, qPrintable(instrId));
                        Segment* segment = score->tick2segment(f.ticks(), true, Segment::Type::ChordRest, true);
                        if (!segment)
                              logger->logError(QString("segment for instrument change at tick %1 not found")
                                               .arg(tick), xmlreader);
                        else if (!mxmlDrumset.contains(instrId))
                              logger->logError(QString("changed instrument '%1' at tick %2 not found in part '%3'")
                                               .arg(instrId).arg(tick).arg(partId), xmlreader);
                        else {
                              MusicXMLDrumInstrument mxmlInstr = mxmlDrumset.value(instrId);
                              Instrument instr = createInstrument(mxmlInstr);
                              //qDebug("instr %p", &instr);

                              InstrumentChange* ic = new InstrumentChange(instr, score);
                              ic->setTrack(track);

                              // if there is already a staff text at this tick / track,
                              // delete it and use its text here instead of "Instrument change"
                              QString text = findDeleteStaffText(segment, track);
                              ic->setXmlText(text.isEmpty() ? "Instrument change" : text);
                              segment->add(ic); // note: includes part::setInstrument(instr);

                              // setMidiChannel() depends on setInstrument() already been done
                              if (mxmlInstr.midiChannel >= 0) part->setMidiChannel(mxmlInstr.midiChannel);
                              }
                        }
                  prevInstrId = instrId;
                  }
            }
      }

//---------------------------------------------------------
//   text2syms
//---------------------------------------------------------

/**
 Convert SMuFL code points to MuseScore <sym>...</sym>
 */

static QString text2syms(const QString& t)
      {
      //QTime time;
      //time.start();

      // first create a map from symbol (Unicode) text to symId
      // note that this takes about 1 msec on a Core i5,
      // caching does not gain much

      ScoreFont* sf = ScoreFont::fallbackFont();
      QMap<QString, SymId> map;
      int maxStringSize = 0;        // maximum string size found

      for (int i = int(SymId::noSym); i < int(SymId::lastSym); ++i) {
            SymId id((SymId(i)));
            QString string(sf->toString(id));
            // insert all syms except space to prevent matching all regular spaces
            if (id != SymId::space)
                  map.insert(string, id);
            if (string.size() > maxStringSize)
                  maxStringSize = string.size();
            }
      //qDebug("text2syms map count %d maxsz %d filling time elapsed: %d ms",
      //       map.size(), maxStringSize, time.elapsed());

      // then look for matches
      QString in = t;
      QString res;

      while (in != "") {
            // try to find the largest match possible
            int maxMatch = qMin(in.size(), maxStringSize);
            QString sym;
            while (maxMatch > 0) {
                  QString toBeMatched = in.left(maxMatch);
                  if (map.contains(toBeMatched)) {
                        sym = Sym::id2name(map.value(toBeMatched));
                        break;
                        }
                  maxMatch--;
                  }
            if (maxMatch > 0) {
                  // found a match, add sym to res and remove match from string in
                  res += "<sym>";
                  res += sym;
                  res += "</sym>";
                  in.remove(0, maxMatch);
                  }
            else {
                  // not found, move one char from res to in
                  res += in.left(1);
                  in.remove(0, 1);
                  }
            }

      //qDebug("text2syms total time elapsed: %d ms, res '%s'", time.elapsed(), qPrintable(res));
      return res;
      }

//---------------------------------------------------------
//   decodeEntities
//---------------------------------------------------------

/**
 Decode &#...; in string \a src into UNICODE (utf8) character.
 */

static QString decodeEntities( const QString& src )
      {
      QString ret(src);
      QRegExp re("&#([0-9]+);");
      re.setMinimal(true);

      int pos = 0;
      while ( (pos = re.indexIn(src, pos)) != -1 ) {
            ret = ret.replace(re.cap(0), QChar(re.cap(1).toInt(0,10)));
            pos += re.matchedLength();
            }
      return ret;
      }

//---------------------------------------------------------
//   nextPartOfFormattedString
//---------------------------------------------------------

// TODO: probably should be shared between pass 1 and 2

/**
 Read the next part of a MusicXML formatted string and convert to MuseScore internal encoding.
 */

static QString nextPartOfFormattedString(QXmlStreamReader& e)
      {
      //QString lang       = e.attribute(QString("xml:lang"), "it");
      QString fontWeight = e.attributes().value("font-weight").toString();
      QString fontSize   = e.attributes().value("font-size").toString();
      QString fontStyle  = e.attributes().value("font-style").toString();
      QString underline  = e.attributes().value("underline").toString();
      QString fontFamily = e.attributes().value("font-family").toString();
      // TODO: color, enclosure, yoffset in only part of the text, ...

      QString txt        = e.readElementText();
      // replace HTML entities
      txt = decodeEntities(txt);
      QString syms       = text2syms(txt);

      QString importedtext;

      if (!fontSize.isEmpty()) {
            bool ok = true;
            float size = fontSize.toFloat(&ok);
            if (ok)
                  importedtext += QString("<font size=\"%1\"/>").arg(size);
            }
      if (!fontFamily.isEmpty() && txt == syms) {
            // add font family only if no <sym> replacement made
            importedtext += QString("<font face=\"%1\"/>").arg(fontFamily);
            }
      if (fontWeight == "bold")
            importedtext += "<b>";
      if (fontStyle == "italic")
            importedtext += "<i>";
      if (!underline.isEmpty()) {
            bool ok = true;
            int lines = underline.toInt(&ok);
            if (ok && (lines > 0))  // 1,2, or 3 underlines are imported as single underline
                  importedtext += "<u>";
            else
                  underline = "";
            }
      if (txt == syms) {
            txt.replace(QString("\r"), QString("")); // convert Windows line break \r\n -> \n
            importedtext += txt.toHtmlEscaped();
            }
      else {
            // <sym> replacement made, should be no need for line break or other conversions
            importedtext += syms;
            }
      if (underline != "")
            importedtext += "</u>";
      if (fontStyle == "italic")
            importedtext += "</i>";
      if (fontWeight == "bold")
            importedtext += "</b>";
      //qDebug("importedtext '%s'", qPrintable(importedtext));
      return importedtext;
      }

//---------------------------------------------------------
//   addLyric
//---------------------------------------------------------

/**
 Add a single lyric to the score or delete it (if number too high)
 */

static void addLyric(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
                     ChordRest* cr, Lyrics* l, int lyricNo, MusicXmlLyricsExtend& extendedLyrics)
      {
      if (lyricNo > MAX_LYRICS) {
            logger->logError(QString("too much lyrics (>%1)")
                             .arg(MAX_LYRICS), xmlreader);
            delete l;
            }
      else {
            l->setNo(lyricNo);
            cr->add(l);
            extendedLyrics.setExtend(lyricNo, cr->track(), cr->tick());
            }
      }

//---------------------------------------------------------
//   addLyrics
//---------------------------------------------------------

/**
 Add a notes lyrics to the score
 */

static void addLyrics(MxmlLogger* logger, const QXmlStreamReader* const xmlreader,
                      ChordRest* cr,
                      QMap<int, Lyrics*>& numbrdLyrics,
                      QSet<Lyrics*>& extLyrics,
                      MusicXmlLyricsExtend& extendedLyrics)
      {
      int lyricNo = -1;
      for (QMap<int, Lyrics*>::const_iterator i = numbrdLyrics.constBegin(); i != numbrdLyrics.constEnd(); ++i) {
            lyricNo = i.key();
            Lyrics* l = i.value();
            addLyric(logger, xmlreader, cr, l, lyricNo, extendedLyrics);
            if (extLyrics.contains(l))
                  extendedLyrics.addLyric(l);
            }
      }

//---------------------------------------------------------
//   addElemOffset
//---------------------------------------------------------

static void addElemOffset(Element* el, int track, const QString& placement, Measure* measure, int tick)
      {
      /*
       qDebug("addElem el %p track %d placement %s tick %d",
       el, track, qPrintable(placement), tick);
       */

      // calc y offset assuming five line staff and default style
      // note that required y offset is element type dependent
      const qreal stafflines = 5; // assume five line staff, but works OK-ish for other sizes too
      qreal offsAbove = 0;
      qreal offsBelow = 0;
      if (el->type() == Element::Type::TEMPO_TEXT || el->type() == Element::Type::REHEARSAL_MARK) {
            offsAbove = 0;
            offsBelow = 8 + (stafflines - 1);
            }
      else if (el->type() == Element::Type::TEXT || el->type() == Element::Type::STAFF_TEXT) {
            offsAbove = 0;
            offsBelow = 6 + (stafflines - 1);
            }
      else if (el->type() == Element::Type::SYMBOL) {
            offsAbove = -2;
            offsBelow =  4 + (stafflines - 1);
            }
      else if (el->type() == Element::Type::DYNAMIC) {
            offsAbove = -5.75 - (stafflines - 1);
            offsBelow = -0.75;
            }
      else
            qDebug("addElem el %p unsupported type %d",
                   el, int(el->type()));  //TODO

      // move to correct position
      // TODO: handle rx, ry
      qreal y = 0;
      if (placement == "above") y += offsAbove;
      if (placement == "below") y += offsBelow;
      //qDebug("   y = %g", y);
      y *= el->score()->spatium();
      el->setUserOff(QPoint(0, y));
      el->setTrack(track);
      Segment* s = measure->getSegment(Segment::Type::ChordRest, tick);
      s->add(el);
      }

//---------------------------------------------------------
//   tupletAssert -- check assertions for tuplet handling
//---------------------------------------------------------

/**
 Check assertions for tuplet handling. If this fails, MusicXML
 import will almost certainly break in non-obvious ways.
 Should never happen, thus it is OK to quit the application.
 */

#if 0
static void tupletAssert()
      {
      if (!(int(TDuration::DurationType::V_BREVE)      == int(TDuration::DurationType::V_LONG)    + 1
            && int(TDuration::DurationType::V_WHOLE)   == int(TDuration::DurationType::V_BREVE)   + 1
            && int(TDuration::DurationType::V_HALF)    == int(TDuration::DurationType::V_WHOLE)   + 1
            && int(TDuration::DurationType::V_QUARTER) == int(TDuration::DurationType::V_HALF)    + 1
            && int(TDuration::DurationType::V_EIGHTH)  == int(TDuration::DurationType::V_QUARTER) + 1
            && int(TDuration::DurationType::V_16TH)    == int(TDuration::DurationType::V_EIGHTH)  + 1
            && int(TDuration::DurationType::V_32ND)    == int(TDuration::DurationType::V_16TH)    + 1
            && int(TDuration::DurationType::V_64TH)    == int(TDuration::DurationType::V_32ND)    + 1
            && int(TDuration::DurationType::V_128TH)   == int(TDuration::DurationType::V_64TH)    + 1
            && int(TDuration::DurationType::V_256TH)   == int(TDuration::DurationType::V_128TH)   + 1
            )) {
            qFatal("tupletAssert() failed");
            }
      }
#endif

//---------------------------------------------------------
//   smallestTypeAndCount
//---------------------------------------------------------

/**
 Determine the smallest note type and the number of those
 present in a ChordRest.
 For a note without dots the type equals the note type
 and count is one.
 For a single dotted note the type equals half the note type
 and count is three.
 A double dotted note is similar.
 Note: code assumes when duration().type() is incremented,
 the note length is divided by two, checked by tupletAssert().
 */

static void smallestTypeAndCount(ChordRest const* const cr, int& type, int& count)
      {
      type = int(cr->durationType().type());
      count = 1;
      switch (cr->durationType().dots()) {
            case 0:
                  // nothing to do
                  break;
            case 1:
                  type += 1; // next-smaller type
                  count = 3;
                  break;
            case 2:
                  type += 2; // next-next-smaller type
                  count = 7;
                  break;
            default:
                  qDebug("smallestTypeAndCount() does not support more than 2 dots");
            }
      }

//---------------------------------------------------------
//   matchTypeAndCount
//---------------------------------------------------------

/**
 Given two note types and counts, if the types are not equal,
 make them equal by successively doubling the count of the
 largest type.
 */

static void matchTypeAndCount(int& type1, int& count1, int& type2, int& count2)
      {
      while (type1 < type2) {
            type1++;
            count1 *= 2;
            }
      while (type2 < type1) {
            type2++;
            count2 *= 2;
            }
      }

//---------------------------------------------------------
//   determineTupletTypeAndCount
//---------------------------------------------------------

/**
 Determine type and number of smallest notes in the tuplet
 */

static void determineTupletTypeAndCount(Tuplet* t, int& tupletType, int& tupletCount)
      {
      int elemCount   = 0; // number of tuplet elements handled

      foreach (DurationElement* de, t->elements()) {
            if (de->type() == Element::Type::CHORD || de->type() == Element::Type::REST) {
                  ChordRest* cr = static_cast<ChordRest*>(de);
                  if (elemCount == 0) {
                        // first note: init variables
                        smallestTypeAndCount(cr, tupletType, tupletCount);
                        }
                  else {
                        int noteType = 0;
                        int noteCount = 0;
                        smallestTypeAndCount(cr, noteType, noteCount);
                        // match the types
                        matchTypeAndCount(tupletType, tupletCount, noteType, noteCount);
                        tupletCount += noteCount;
                        }
                  }
            elemCount++;
            }
      }

//---------------------------------------------------------
//   determineTupletBaseLen
//---------------------------------------------------------

/**
 Determine tuplet baseLen as determined by the tuplet ratio,
 and type and number of smallest notes in the tuplet.

 Example: baselen of a 3:2 tuplet with 1/16, 1/8, 1/8 and 1/16
 is 1/8. For this tuplet smalles note is 1/16, count is 6.
 */

// TODO: this is defined twice, remove one

static TDuration determineTupletBaseLen(Tuplet* t)
      {
      int tupletType  = 0; // smallest note type in the tuplet
      int tupletCount = 0; // number of smallest notes in the tuplet

      // first determine type and number of smallest notes in the tuplet
      determineTupletTypeAndCount(t, tupletType, tupletCount);

      // sanity check:
      // for a 3:2 tuplet, count must be a multiple of 3
      if (tupletCount % t->ratio().numerator()) {
            qDebug("determineTupletBaseLen(%p) cannot divide count %d by %d", t, tupletCount, t->ratio().numerator());
            return TDuration();
            }

      // calculate baselen in smallest notes
      tupletCount /= t->ratio().numerator();

      // normalize
      while (tupletCount > 1 && (tupletCount % 2) == 0) {
            tupletCount /= 2;
            tupletType  -= 1;
            }

      return TDuration(TDuration::DurationType(tupletType));
      }

//---------------------------------------------------------
//   isTupletFilled
//---------------------------------------------------------

/**
 Determine if the tuplet contains the required number of notes,
 either (1) of the specified normal type
 or (2) the amount of the smallest notes in the tuplet equals
 actual notes.

 Example (1): a 3:2 tuplet with a 1/4 and a 1/8 note is filled
 if normal type is 1/8, it is not filled if normal
 type is 1/4.

 Example (2): a 3:2 tuplet with a 1/4 and a 1/8 note is filled.

 Use note types instead of duration to prevent errors due to rounding.
 */

// TODO: this is defined twice, remove one

static bool isTupletFilled(Tuplet* t, TDuration normalType)
      {
      if (!t) return false;

      int tupletType  = 0; // smallest note type in the tuplet
      int tupletCount = 0; // number of smallest notes in the tuplet

      // first determine type and number of smallest notes in the tuplet
      determineTupletTypeAndCount(t, tupletType, tupletCount);

      // then compare ...
      if (normalType.isValid()) {
            int matchedNormalType  = int(normalType.type());
            int matchedNormalCount = t->ratio().numerator();
            // match the types
            matchTypeAndCount(tupletType, tupletCount, matchedNormalType, matchedNormalCount);
            // ... result scenario (1)
            return tupletCount >= matchedNormalCount;
            }
      else {
            // ... result scenario (2)
            return tupletCount >= t->ratio().numerator();
            }
      }

//---------------------------------------------------------
//   addTupletToChord
//---------------------------------------------------------

/**
 Handle tuplet(s) using parse result tupletDesc
 Tuplets with <actual-notes> and <normal-notes> but without <tuplet>
 are handled correctly.
 TODO Nested tuplets are not (yet) supported.

 Note that cr must be initialized: fields measure, score, tick
 and track are used.
 */

void addTupletToChord(ChordRest* cr, Tuplet*& tuplet, bool& tuplImpl,
                      const Fraction& timeMod, const MusicXmlTupletDesc& tupletDesc,
                      const TDuration normalType)
      {
      int actualNotes = timeMod.denominator();
      int normalNotes = timeMod.numerator();

      // check for obvious errors
      if (tupletDesc.type == MxmlStartStop::START && tuplet) {
            qDebug("tuplet already started"); // TODO
            // TODO: how to recover ?
            }
      if (tupletDesc.type == MxmlStartStop::STOP && !tuplet) {
            qDebug("tuplet stop but no tuplet started"); // TODO
            // TODO: how to recover ?
            }

      // Tuplet are either started by the tuplet start
      // or when the time modification is first found.
      if (!tuplet) {
            if (tupletDesc.type == MxmlStartStop::START
                || (!tuplet && (actualNotes != 1 || normalNotes != 1))) {
                  if (tupletDesc.type != MxmlStartStop::START) {
                        tuplImpl = true;
                        // report missing start
                        qDebug("implicit tuplet start cr %p tick %d track %d", cr, cr->tick(), cr->track()); // TODO
                        }
                  else
                        tuplImpl = false;
                  // create a new tuplet
                  tuplet = new Tuplet(cr->score());
                  tuplet->setTrack(cr->track());
                  tuplet->setRatio(Fraction(actualNotes, normalNotes));
                  tuplet->setTick(cr->tick());
                  tuplet->setBracketType(tupletDesc.bracket);
                  tuplet->setNumberType(tupletDesc.shownumber);
                  // TODO type, placement, bracket
                  tuplet->setParent(cr->measure());
                  }
            }

      // Add chord to the current tuplet.
      // Must also check for actual/normal notes to prevent
      // adding one chord too much if tuplet stop is missing.
      if (tuplet && !(actualNotes == 1 && normalNotes == 1)) {
            cr->setTuplet(tuplet);
            tuplet->add(cr);
            }

      // Tuplets are stopped by the tuplet stop
      // or when the tuplet is filled completely
      // (either with knowledge of the normal type
      // or as a last resort calculated based on
      // actual and normal notes plus total duration)
      // or when the time-modification is not found.
      if (tuplet) {
            if (tupletDesc.type == MxmlStartStop::STOP
                || (tuplImpl && isTupletFilled(tuplet, normalType))
                || (actualNotes == 1 && normalNotes == 1)) {
                  // set baselen
                  TDuration td = determineTupletBaseLen(tuplet);
                  // qDebug("stop tuplet %p basetype %d", tuplet, tupletType);
                  tuplet->setBaseLen(td);
                  Fraction f(normalNotes, td.fraction().denominator());
                  f.reduce();
                  tuplet->setDuration(f);
                  // TODO determine usefulness of following check
                  int totalDuration = 0;
                  foreach (DurationElement* de, tuplet->elements()) {
                        if (de->type() == Element::Type::CHORD || de->type() == Element::Type::REST) {
                              totalDuration+=de->globalDuration().ticks();
                              }
                        }
                  if (!(totalDuration && normalNotes)) {
                        qDebug("MusicXML::import: tuplet stop but bad duration"); // TODO
                        }
                  tuplet = 0;
                  }
            }
      }

//---------------------------------------------------------
//   addArticulationToChord
//---------------------------------------------------------

/**
 Add Articulation to Chord.
 */

static void addArticulationToChord(ChordRest* cr, ArticulationType articSym, QString dir)
      {
      Articulation* na = new Articulation(cr->score());
      na->setArticulationType(articSym);
      if (dir == "up") {
            na->setUp(true);
            na->setAnchor(ArticulationAnchor::TOP_STAFF);
            }
      else if (dir == "down") {
            na->setUp(false);
            na->setAnchor(ArticulationAnchor::BOTTOM_STAFF);
            }
      cr->add(na);
      }

//---------------------------------------------------------
//   addMordentToChord
//---------------------------------------------------------

/**
 Add Mordent to Chord.
 */

static void addMordentToChord(ChordRest* cr, QString name, QString attrLong, QString attrAppr, QString attrDep)
      {
      ArticulationType articSym = ArticulationType::ARTICULATIONS; // legal but impossible ArticulationType value here indicating "not found"
      if (name == "inverted-mordent") {
            if ((attrLong == "" || attrLong == "no") && attrAppr == "" && attrDep == "") articSym = ArticulationType::Prall;
            else if (attrLong == "yes" && attrAppr == "" && attrDep == "") articSym = ArticulationType::PrallPrall;
            else if (attrLong == "yes" && attrAppr == "below" && attrDep == "") articSym = ArticulationType::UpPrall;
            else if (attrLong == "yes" && attrAppr == "above" && attrDep == "") articSym = ArticulationType::DownPrall;
            else if (attrLong == "yes" && attrAppr == "" && attrDep == "below") articSym = ArticulationType::PrallDown;
            else if (attrLong == "yes" && attrAppr == "" && attrDep == "above") articSym = ArticulationType::PrallUp;
            }
      else if (name == "mordent") {
            if ((attrLong == "" || attrLong == "no") && attrAppr == "" && attrDep == "") articSym = ArticulationType::Mordent;
            else if (attrLong == "yes" && attrAppr == "" && attrDep == "") articSym = ArticulationType::PrallMordent;
            else if (attrLong == "yes" && attrAppr == "below" && attrDep == "") articSym = ArticulationType::UpMordent;
            else if (attrLong == "yes" && attrAppr == "above" && attrDep == "") articSym = ArticulationType::DownMordent;
            }
      if (articSym != ArticulationType::ARTICULATIONS) {
            Articulation* na = new Articulation(cr->score());
            na->setArticulationType(articSym);
            cr->add(na);
            }
      else
            qDebug("unknown ornament: name '%s' long '%s' approach '%s' departure '%s'",
                   qPrintable(name), qPrintable(attrLong), qPrintable(attrAppr), qPrintable(attrDep));  // TODO
      }

//---------------------------------------------------------
//   addMxmlArticulationToChord
//---------------------------------------------------------

/**
 Add a MusicXML articulation to a chord as a "simple" MuseScore articulation.
 These are the articulations that can be
 - represented by an enum ArticulationType
 - added to a ChordRest
 Return true (articulation recognized and handled)
 or false (articulation not recognized).
 Note simple implementation: MusicXML syntax is not strictly
 checked, the articulations parent element does not matter.
 */

static bool addMxmlArticulationToChord(ChordRest* cr, QString mxmlName)
      {
      QMap<QString, ArticulationType> map; // map MusicXML articulation name to MuseScore symbol
      map["accent"]           = ArticulationType::Sforzatoaccent;
      map["staccatissimo"]    = ArticulationType::Staccatissimo;
      map["staccato"]         = ArticulationType::Staccato;
      map["tenuto"]           = ArticulationType::Tenuto;
      map["turn"]             = ArticulationType::Turn;
      map["inverted-turn"]    = ArticulationType::Reverseturn;
      map["stopped"]          = ArticulationType::Plusstop;
      map["up-bow"]           = ArticulationType::Upbow;
      map["down-bow"]         = ArticulationType::Downbow;
      map["detached-legato"]  = ArticulationType::Portato;
      map["spiccato"]         = ArticulationType::Staccatissimo;
      map["snap-pizzicato"]   = ArticulationType::Snappizzicato;
      map["schleifer"]        = ArticulationType::Schleifer;
      map["open-string"]      = ArticulationType::Ouvert;
      map["thumb-position"]   = ArticulationType::ThumbPosition;

      if (map.contains(mxmlName)) {
            addArticulationToChord(cr, map.value(mxmlName), "");
            return true;
            }
      else
            return false;
      }

//---------------------------------------------------------
//   convertNotehead
//---------------------------------------------------------

/**
 Convert a MusicXML notehead name to a MuseScore headgroup.
 */

static NoteHead::Group convertNotehead(QString mxmlName)
      {
      QMap<QString, int> map; // map MusicXML notehead name to a MuseScore headgroup
      map["slash"] = 5;
      map["triangle"] = 3;
      map["diamond"] = 2;
      map["x"] = 1;
      map["circle-x"] = 6;
      map["do"] = 7;
      map["re"] = 8;
      map["mi"] = 4;
      map["fa"] = 9;
      map["so"] = 12;
      map["la"] = 10;
      map["ti"] = 11;
      map["normal"] = 0;

      if (map.contains(mxmlName))
            return NoteHead::Group(map.value(mxmlName));
      else
            qDebug("unknown notehead %s", qPrintable(mxmlName));  // TODO
      // default: return 0
      return NoteHead::Group::HEAD_NORMAL;
      }

//---------------------------------------------------------
//   addTextToNote
//---------------------------------------------------------

/**
 Add Text to Note.
 */

static void addTextToNote(int l, int c, QString txt, TextStyleType style, Score* score, Note* note)
      {
      if (note) {
            if (!txt.isEmpty()) {
                  Text* t = new Fingering(score);
                  t->setTextStyleType(style);
                  t->setPlainText(txt);
                  note->add(t);
                  }
            }
      else
            qDebug("%s", qPrintable(QString("Error at line %1 col %2: no note for text").arg(l).arg(c)));       // TODO
      }

//---------------------------------------------------------
//   addFermata
//---------------------------------------------------------

/**
 Add a MusicXML fermata.
 Note: MusicXML common.mod: "The fermata type is upright if not specified."
 */

static void addFermata(ChordRest* cr, const QString type, const ArticulationType articSym)
      {
      if (type == "upright" || type == "")
            addArticulationToChord(cr, articSym, "up");
      else if (type == "inverted")
            addArticulationToChord(cr, articSym, "down");
      else
            qDebug("unknown fermata type '%s'", qPrintable(type));
      }

//---------------------------------------------------------
//   setSLinePlacement
//---------------------------------------------------------

/**
 Helper for direction().
 SLine placement is modified by changing the first segments user offset
 As the SLine has just been created, it does not have any segment yet
 */

static void setSLinePlacement(SLine* sli, const QString placement)
      {
      /*
       qDebug("setSLinePlacement sli %p type %d s=%g pl='%s'",
       sli, sli->type(), sli->score()->spatium(), qPrintable(placement));
       */

      // calc y offset assuming five line staff and default style
      // note that required y offset is element type dependent
      const qreal stafflines = 5;       // assume five line staff, but works OK-ish for other sizes too
      qreal offsAbove = 0;
      qreal offsBelow = 0;
      if (sli->type() == Element::Type::PEDAL || sli->type() == Element::Type::HAIRPIN) {
            offsAbove = -6 - (stafflines - 1);
            offsBelow = -1;
            }
      else if (sli->type() == Element::Type::TEXTLINE) {
            offsAbove = 0;
            offsBelow =  5 + 3 + (stafflines - 1);
            }
      else if (sli->type() == Element::Type::OTTAVA) {
            // ignore
            }
      else
            qDebug("setSLinePlacement sli %p unsupported type %d",
                   sli, int(sli->type()));

      // move to correct position
      qreal y = 0;
      if (placement == "above") y += offsAbove;
      if (placement == "below") y += offsBelow;
      // add linesegment containing the user offset
      LineSegment* tls= sli->createLineSegment();
      //qDebug("   y = %g", y);
      y *= sli->score()->spatium();
      tls->setUserOff(QPointF(0, y));
      sli->add(tls);
      }

//---------------------------------------------------------
//   handleSpannerStart
//---------------------------------------------------------

// note that in case of overlapping spanners, handleSpannerStart is called for every spanner
// as spanners QMap allows only one value per key, this does not hurt at all

static void handleSpannerStart(SLine* new_sp, int track, QString& placement, int tick, MusicXmlSpannerMap& spanners)
      {
      //qDebug("handleSpannerStart(sp %p, track %d, tick %d)", new_sp, track, tick);
      new_sp->setTrack(track);
      setSLinePlacement(new_sp, placement);
      spanners[new_sp] = QPair<int, int>(tick, -1);
      }

//---------------------------------------------------------
//   handleSpannerStop
//---------------------------------------------------------

static void handleSpannerStop(SLine* cur_sp, int track2, int tick, MusicXmlSpannerMap& spanners)
      {
      //qDebug("handleSpannerStop(sp %p, track2 %d, tick %d)", cur_sp, track2, tick);
      if (!cur_sp)
            return;

      cur_sp->setTrack2(track2);
      spanners[cur_sp].second = tick;
      }

//---------------------------------------------------------
//   The MusicXML parser, pass 2
//---------------------------------------------------------

//---------------------------------------------------------
//   MusicXMLParserPass2
//---------------------------------------------------------

MusicXMLParserPass2::MusicXMLParserPass2(Score* score, MusicXMLParserPass1& pass1, MxmlLogger* logger)
      : _divs(0), _score(score), _pass1(pass1), _logger(logger)
      {
      // nothing
      }

//---------------------------------------------------------
//   initPartState
//---------------------------------------------------------

/**
 Initialize members as required for reading the MusicXML part element.
 TODO: factor out part reading into a separate class
 TODO: preferably use automatically initialized variables
 Note that Qt automatically initializes new elements in QVector (tuplets).
 */

void MusicXMLParserPass2::initPartState(const QString& partId)
      {
      _timeSigDura = Fraction(0, 0);             // invalid
      int nstaves = _pass1.getPart(partId)->nstaves();
      _tuplets.resize(nstaves * VOICES);
      _tuplImpls.resize(nstaves * VOICES);
      _tie    = 0;
      _lastVolta = 0;
      _hasDrumset = false;
      for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
            _slurs[i] = SlurDesc();
      for (int i = 0; i < MAX_BRACKETS; ++i)
            _brackets[i] = 0;
      for (int i = 0; i < MAX_DASHES; ++i)
            _dashes[i] = 0;
      for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
            _ottavas[i] = 0;
      for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
            _hairpins[i] = 0;
      for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
            _trills[i] = 0;
      for (int i = 0; i < MAX_NUMBER_LEVEL; ++i)
            _glissandi[i][0] = _glissandi[i][1] = 0;
      _pedal = 0;
      _pedalContinue = 0;
      _harmony = 0;
      _tremStart = 0;
      _figBass = 0;
      //      glissandoText = "";
      //      glissandoColor = "";
      _multiMeasureRestCount = -1;
      _extendedLyrics.init();
      }

//---------------------------------------------------------
// multi-measure rest state handling
//---------------------------------------------------------

// If any multi-measure rest is found, the "create multi-measure rest" style setting is enabled.
// First measure in a multi-measure rest gets setBreakMultiMeasureRest(true), then count down
// the remaining number of measures.
// The first measure after a multi-measure rest gets setBreakMultiMeasureRest(true).
// For all other measures breakMultiMeasureRest is unchanged (stays default (false)).

//---------------------------------------------------------
//   setMultiMeasureRestCount
//---------------------------------------------------------

/**
 Set the multi-measure rest counter.
 */


void MusicXMLParserPass2::setMultiMeasureRestCount(int count)
      {
      _multiMeasureRestCount = count;
      }

//---------------------------------------------------------
//   getAndDecMultiMeasureRestCount
//---------------------------------------------------------

/**
 Return current multi-measure rest counter.
 Decrement counter if possible (not beyond -1).
 */

int MusicXMLParserPass2::getAndDecMultiMeasureRestCount()
      {
      int res = _multiMeasureRestCount;
      if (_multiMeasureRestCount >= 0)
            _multiMeasureRestCount--;
      return res;
      }

//---------------------------------------------------------
//   skipLogCurrElem
//---------------------------------------------------------

/**
 Skip the current element, log debug as info.
 */

void MusicXMLParserDirection::skipLogCurrElem()
      {
      //_logger->logDebugInfo(QString("skipping '%1'").arg(_e.name().toString()), &_e);
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   skipLogCurrElem
//---------------------------------------------------------

/**
 Skip the current element, log debug as info.
 */

void MusicXMLParserPass2::skipLogCurrElem()
      {
      //_logger->logDebugInfo(QString("skipping '%1'").arg(_e.name().toString()), &_e);
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   parse
//---------------------------------------------------------

/**
 Parse MusicXML in \a device and extract pass 2 data.
 */

Score::FileError MusicXMLParserPass2::parse(QIODevice* device)
      {
      //qDebug("MusicXMLParserPass2::parse()");
      _e.setDevice(device);
      Score::FileError res = parse();
      //qDebug("MusicXMLParserPass2::parse() res %d", int(res));
      return res;
      }

//---------------------------------------------------------
//   parse
//---------------------------------------------------------

/**
 Start the parsing process, after verifying the top-level node is score-partwise
 */

Score::FileError MusicXMLParserPass2::parse()
      {
      bool found = false;
      while (_e.readNextStartElement()) {
            if (_e.name() == "score-partwise") {
                  found = true;
                  scorePartwise();
                  }
            else {
                  _logger->logError("this is not a MusicXML score-partwise file", &_e);
                  _e.skipCurrentElement();
                  return Score::FileError::FILE_BAD_FORMAT;
                  }
            }

      if (!found) {
            _logger->logError("this is not a MusicXML score-partwise file", &_e);
            return Score::FileError::FILE_BAD_FORMAT;
            }

      return Score::FileError::FILE_NO_ERROR;
      }

//---------------------------------------------------------
//   scorePartwise
//---------------------------------------------------------

/**
 Parse the MusicXML top-level (XPath /score-partwise) node.
 */

void MusicXMLParserPass2::scorePartwise()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "score-partwise");

      while (_e.readNextStartElement()) {
            if (_e.name() == "part") {
                  part();
                  }
            else if (_e.name() == "part-list")
                  partList();
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   partList
//---------------------------------------------------------

/**
 Parse the /score-partwise/part-list node.
 */

void MusicXMLParserPass2::partList()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "part-list");

      while (_e.readNextStartElement()) {
            if (_e.name() == "score-part")
                  scorePart();
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   scorePart
//---------------------------------------------------------

// Parse the /score-partwise/part-list/score-part node.
// TODO: nothing required for pass 2 ?

void MusicXMLParserPass2::scorePart()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "score-part");

      while (_e.readNextStartElement()) {
            if (_e.name() == "midi-instrument")
                  _e.skipCurrentElement();  // skip but don't log
            else if (_e.name() == "score-instrument")
                  _e.skipCurrentElement();  // skip but don't log
            else if (_e.name() == "part-name")
                  _e.skipCurrentElement();  // skip but don't log
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   part
//---------------------------------------------------------

/**
 Parse the /score-partwise/part node.
 */

void MusicXMLParserPass2::part()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "part");
      const QString id = _e.attributes().value("id").toString();

      if (!_pass1.hasPart(id)) {
            _logger->logError(QString("MusicXMLParserPass2::part cannot find part '%1'").arg(id), &_e);
            skipLogCurrElem();
            }

      initPartState(id);

      const MusicXMLDrumset& mxmlDrumset = _pass1.getDrumset(id);
      _hasDrumset = hasDrumset(mxmlDrumset);

      // set the parts first instrument
      QString instrId = _pass1.getInstrList(id).instrument(Fraction(0, 1));
      setFirstInstrument(_logger, &_e, _pass1.getPart(id), id, instrId, mxmlDrumset);

      // set the part name
      auto mxmlPart = _pass1.getMusicXmlPart(id);
      _pass1.getPart(id)->setPartName(mxmlPart.getName());
      if (mxmlPart.getPrintName())
            _pass1.getPart(id)->setLongName(mxmlPart.getName());
      if (mxmlPart.getPrintAbbr())
            _pass1.getPart(id)->setPlainShortName(mxmlPart.getAbbr());
      // try to prevent an empty track name
      if (_pass1.getPart(id)->partName() == "")
            _pass1.getPart(id)->setPartName(mxmlDrumset[instrId].name);

#ifdef DEBUG_VOICE_MAPPER
      VoiceList voicelist = _pass1.getVoiceList(id);
      // debug: print voice mapper contents
      qDebug("voiceMapperStats: part '%s'", qPrintable(id));
      for (QMap<QString, Ms::VoiceDesc>::const_iterator i = voicelist.constBegin(); i != voicelist.constEnd(); ++i) {
            qDebug("voiceMapperStats: voice %s staff data %s",
                   qPrintable(i.key()), qPrintable(i.value().toString()));
            }
#endif

      // read the measures
      int nr = 0; // current measure sequence number
      while (_e.readNextStartElement()) {
            if (_e.name() == "measure") {
                  Fraction t = _pass1.getMeasureStart(nr);
                  if (t.isValid())
                        measure(id, t);
                  else {
                        _logger->logError(QString("no valid start time for measure %1").arg(nr + 1), &_e);
                        _e.skipCurrentElement();
                        }
                  ++nr;
                  }
            else
                  skipLogCurrElem();
            }

      // stop all remaining extends for this part
      Measure* lm = _pass1.getPart(id)->score()->lastMeasure();
      if (lm) {
            int strack = _pass1.trackForPart(id);
            int etrack = strack + _pass1.getPart(id)->nstaves() * VOICES;
            int lastTick = lm->tick() + lm->ticks();
            for (int trk = strack; trk < etrack; trk++)
                  _extendedLyrics.setExtend(-1, trk, lastTick);
            }

      //qDebug("spanner list:");
      auto i = _spanners.constBegin();
      while (i != _spanners.constEnd()) {
            Spanner* sp = i.key();
            int tick1 = i.value().first;
            int tick2 = i.value().second;
            //qDebug("spanner %p tp %hhd tick1 %d tick2 %d track %d track2 %d",
            //       sp, sp->type(), tick1, tick2, sp->track(), sp->track2());
            sp->setTick(tick1);
            sp->setTick2(tick2);
            sp->score()->addElement(sp);
            ++i;
            }
      _spanners.clear();

      // determine if the part contains a drumset
      // this is the case if any instrument has a midi-unpitched element,
      // (which stored in the MusicXMLDrumInstrument pitch field)
      // if the part contains a drumset, Drumset drumset is intialized

      Drumset* drumset = new Drumset;
      const MusicXMLDrumset& mxmlDrumsetAfterPass2 = _pass1.getDrumset(id);
      initDrumset(drumset, mxmlDrumsetAfterPass2);

      // debug: dump the instrument map
      /*
            {
            qDebug("instrlist");
            auto il = _pass1.getInstrList(id);
            for (auto it = il.cbegin(); it != il.cend(); ++it) {
                  Fraction f = (*it).first;
                  qDebug("pass2: instrument map: tick %s (%d) instr '%s'", qPrintable(f.print()), f.ticks(), qPrintable((*it).second));
                  }
            }
      */

      if (_hasDrumset) {
            // set staff type to percussion if incorrectly imported as pitched staff
            // Note: part has been read, staff type already set based on clef type and staff-details
            // but may be incorrect for a percussion staff that does not use a percussion clef
            setStaffTypePercussion(_pass1.getPart(id), drumset);
            }
      else {
            // drumset is not needed
            delete drumset;
            // set the instruments for this part
            setPartInstruments(_logger, &_e, _pass1.getPart(id), id, _score, _pass1.getInstrList(id), mxmlDrumset);
            }
      }

//---------------------------------------------------------
//   findMeasure
//---------------------------------------------------------

/**
 In Score \a score find the measure starting at \a tick.
 */

static Measure* findMeasure(Score* score, const int tick)
      {
      for (Measure* m = score->firstMeasure();; m = m->nextMeasure()) {
            if (m && m->tick() == tick)
                  return m;
            }
      return 0;
      }

//---------------------------------------------------------
//   removeBeam
//---------------------------------------------------------

/**
 Set beam mode for all elements and remove the beam
 */

static void removeBeam(Beam*& beam)
      {
      for (int i = 0; i < beam->elements().size(); ++i)
            beam->elements().at(i)->setBeamMode(Beam::Mode::NONE);
      delete beam;
      beam = 0;
      }

//---------------------------------------------------------
//   handleBeamAndStemDir
//---------------------------------------------------------

static void handleBeamAndStemDir(ChordRest* cr, const Beam::Mode bm, const MScore::Direction sd, Beam*& beam)
      {
      if (!cr) return;
      // create a new beam
      if (bm == Beam::Mode::BEGIN) {
            // if currently in a beam, delete it
            if (beam) {
                  qDebug("handleBeamAndStemDir() new beam, removing previous incomplete beam %p", beam);
                  removeBeam(beam);
                  }
            // create a new beam
            beam = new Beam(cr->score());
            beam->setTrack(cr->track());
            beam->setBeamDirection(sd);
            }
      // add ChordRest to beam
      if (beam) {
            // verify still in the same track (switching voices in the middle of a beam is not supported)
            // and in a beam ...
            // (note no check is done on correct order of beam begin/continue/end)
            if (cr->track() != beam->track()) {
                  qDebug("handleBeamAndStemDir() from track %d to track %d bm %d -> abort beam",
                         beam->track(), cr->track(), int(bm));
                  // reset beam mode for all elements and remove the beam
                  removeBeam(beam);
                  }
            else if (bm == Beam::Mode::NONE) {
                  qDebug("handleBeamAndStemDir() in beam, bm Beam::Mode::NONE -> abort beam");
                  // reset beam mode for all elements and remove the beam
                  removeBeam(beam);
                  }
            else if (!(bm == Beam::Mode::BEGIN || bm == Beam::Mode::MID || bm == Beam::Mode::END)) {
                  qDebug("handleBeamAndStemDir() in beam, bm %d -> abort beam", static_cast<int>(bm));
                  // reset beam mode for all elements and remove the beam
                  removeBeam(beam);
                  }
            else {
                  // actually add cr to the beam
                  beam->add(cr);
                  }
            }
      // if no beam, set stem direction on chord itself and set beam to auto
      if (!beam) {
            static_cast<Chord*>(cr)->setStemDirection(sd);
            cr->setBeamMode(Beam::Mode::AUTO);
            }
      // terminate the currect beam and add to the score
      if (beam && bm == Beam::Mode::END)
            beam = 0;
      }


//---------------------------------------------------------
//   markUserAccidentals
//---------------------------------------------------------

/**
 Check for "superfluous" accidentals to mark them as USER accidentals.
 The candidate map alterMap is ordered on note address. Check it here segment after segment.
 */

static void markUserAccidentals(const int firstStaff,
                                const int staves,
                                const Key key,
                                const Measure* measure,
                                const QMap<Note*, int>& alterMap
                                )
      {
      QMap<int, bool> accTmp;

      AccidentalState currAcc;
      currAcc.init(key);
      Segment::Type st = Segment::Type::ChordRest;
      for (Ms::Segment* segment = measure->first(st); segment; segment = segment->next(st)) {
            for (int track = 0; track < staves * VOICES; ++track) {
                  Element* e = segment->element(firstStaff * VOICES + track);
                  if (!e || e->type() != Ms::Element::Type::CHORD)
                        continue;
                  Chord* chord = static_cast<Chord*>(e);
                  foreach (Note* nt, chord->notes()) {
                        if (alterMap.contains(nt)) {
                              int alter = alterMap.value(nt);
                              int ln  = absStep(nt->tpc(), nt->pitch());
                              bool error = false;
                              AccidentalVal currAccVal = currAcc.accidentalVal(ln, error);
                              if (error)
                                    continue;
                              if ((alter == -1
                                   && currAccVal == AccidentalVal::FLAT
                                   && nt->accidental()->accidentalType() == AccidentalType::FLAT
                                   && !accTmp.value(ln, false))
                                  || (alter ==  0
                                      && currAccVal == AccidentalVal::NATURAL
                                      && nt->accidental()->accidentalType() == AccidentalType::NATURAL
                                      && !accTmp.value(ln, false))
                                  || (alter ==  1
                                      && currAccVal == AccidentalVal::SHARP
                                      && nt->accidental()->accidentalType() == AccidentalType::SHARP
                                      && !accTmp.value(ln, false))) {
                                    nt->accidental()->setRole(AccidentalRole::USER);
                                    }
                              else if (nt->accidental()->accidentalType() > AccidentalType::NATURAL
                                       && nt->accidental()->accidentalType() < AccidentalType::END) {
                                    // microtonal accidental
                                    nt->accidental()->setRole(AccidentalRole::USER);
                                    accTmp.insert(ln, false);
                                    }
                              else {
                                    accTmp.insert(ln, true);
                                    }
                              }
                        }
                  }
            }
      }

//---------------------------------------------------------
//   addGraceChordsAfter
//---------------------------------------------------------

/**
 Move \a gac grace chords from grace chord list \a gcl
 to the chord \a c grace note after list
 */

static void addGraceChordsAfter(Chord* c, GraceChordList& gcl, int& gac)
      {
      if (!c)
            return;

      while (gac > 0) {
            if (gcl.size() > 0) {
                  Chord* graceChord = gcl.first();
                  gcl.removeFirst();
                  graceChord->toGraceAfter();
                  c->add(graceChord);        // TODO check if same voice ?
                  qDebug("addGraceChordsAfter chord %p grace after chord %p", c, graceChord);
                  }
            gac--;
            }
      }

//---------------------------------------------------------
//   addGraceChordsBefore
//---------------------------------------------------------

/**
 Move grace chords from grace chord list \a gcl
 to the chord \a c grace note before list
 */

static void addGraceChordsBefore(Chord* c, GraceChordList& gcl)
      {
      for (int i = gcl.size() - 1; i >= 0; i--)
            c->add(gcl.at(i));        // TODO check if same voice ?
      gcl.clear();
      }

//---------------------------------------------------------
//   measure
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure node.
 */

void MusicXMLParserPass2::measure(const QString& partId,
                                  const Fraction time)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "measure");
      QString number = _e.attributes().value("number").toString();
      //qDebug("measure %s start", qPrintable(number));

      Measure* measure = findMeasure(_score, time.ticks());
      if (!measure) {
            _logger->logError(QString("measure at tick %1 not found!").arg(time.ticks()), &_e);
            skipLogCurrElem();
            }

      // handle implicit measure
      if (_e.attributes().value("implicit") == "yes")
            measure->setIrregular(true);

      // set measure's RepeatFlag to none because musicXML is allowing single measure repeat and no ordering in repeat start and end barlines
      measure->setRepeatFlag(Repeat::NONE);

      Fraction mTime; // current time stamp within measure
      Fraction prevTime; // time stamp within measure previous chord
      Chord* prevChord = 0;       // previous chord
      Fraction mDura; // current total measure duration
      GraceChordList gcl; // grace chords collected sofar
      int gac = 0;       // grace after count in the grace chord list
      Beam* beam = 0;       // current beam
      QString cv = "1";       // current voice for chords, default is 1
      FiguredBassList fbl;               // List of figured bass elements under a single note

      // collect candidates for courtesy accidentals to work out at measure end
      QMap<Note*, int> alterMap;

      while (_e.readNextStartElement()) {
            if (_e.name() == "attributes")
                  attributes(partId, measure, (time + mTime).ticks());
            else if (_e.name() == "direction") {
                  MusicXMLParserDirection dir(_e, _score, _pass1, *this, _logger);
                  dir.direction(partId, measure, (time + mTime).ticks(), _spanners);
                  }
            else if (_e.name() == "figured-bass") {
                  FiguredBass* fb = figuredBass();
                  if (fb)
                        fbl.append(fb);
                  }
            else if (_e.name() == "harmony")
                  harmony(partId, measure, time + mTime);
            else if (_e.name() == "note") {
                  Fraction dura;
                  int alt = -10;                    // any number outside range of xml-tag "alter"
                  // note: chord and grace note handling done in note()
                  // dura > 0 iff valid rest or first note of chord found
                  Note* n = note(partId, measure, time + mTime, time + prevTime, dura, cv, gcl, gac, beam, fbl, alt);
                  if (n && !n->chord()->isGrace())
                        prevChord = n->chord();  // remember last non-grace chord
                  if (n && n->accidental() && n->accidental()->accidentalType() != AccidentalType::NONE)
                        alterMap.insert(n, alt);
                  if (dura.isValid() && dura > Fraction(0, 1)) {
                        prevTime = mTime; // save time stamp last chord created
                        mTime += dura;
                        if (mTime > mDura)
                              mDura = mTime;
                        }
                  //qDebug("added note %p chord %p gac %d", n, n ? n->chord() : 0, gac);
                  }
            else if (_e.name() == "forward") {
                  Fraction dura;
                  forward(dura);
                  if (dura.isValid()) {
                        mTime += dura;
                        if (mTime > mDura)
                              mDura = mTime;
                        }
                  }
            else if (_e.name() == "backup") {
                  Fraction dura;
                  backup(dura);
                  if (dura.isValid()) {
                        if (dura <= mTime)
                              mTime -= dura;
                        else {
                              _logger->logError("backup beyond measure start", &_e);
                              mTime.set(0, 1);
                              }
                        }
                  }
            else if (_e.name() == "sound") {
                  QString tempo = _e.attributes().value("tempo").toString();

                  if (!tempo.isEmpty()) {
                        double tpo = tempo.toDouble() / 60;
                        int tick = (time + mTime).ticks();

                        TempoText* t = new TempoText(_score);
                        t->setXmlText(QString("%1 = %2").arg(TempoText::duration2tempoTextString(TDuration(TDuration::DurationType::V_QUARTER))).arg(tempo));
                        t->setTempo(tpo);
                        t->setFollowText(true);

                        _score->setTempo(tick, tpo);

                        addElemOffset(t, _pass1.trackForPart(partId), "above", measure, tick);
                        }
                  _e.skipCurrentElement();
                  }
            else if (_e.name() == "barline")
                  barline(partId, measure);
            else if (_e.name() == "print")
                  print(measure);
            else
                  skipLogCurrElem();

            /*
             qDebug("mTime %s (%s) mDura %s (%s)",
             qPrintable(mTime.print()),
             qPrintable(mTime.reduced().print()),
             qPrintable(mDura.print()),
             qPrintable(mDura.reduced().print()));
             */
            mDura.reduce();
            mTime.reduce();
            }

      // convert remaining grace chords to grace after
      gac = gcl.size();
      addGraceChordsAfter(prevChord, gcl, gac);

      // fill possible gaps in voice 1
      Part* part = _pass1.getPart(partId); // should not fail, we only get here if the part exists
      fillGapsInFirstVoices(measure, part);

      // can't have beams extending into the next measure
      if (beam)
            removeBeam(beam);

      // TODO:
      // - how to handle _timeSigDura.isZero (shouldn't happen ?)
      // - how to handle unmetered music
      if (_timeSigDura.isValid() && !_timeSigDura.isZero())
            measure->setTimesig(_timeSigDura);

      // mark superfluous accidentals as user accidentals
      const int scoreRelStaff = _score->staffIdx(part);
      const Key key = _score->staff(scoreRelStaff)->keySigEvent(time.ticks()).key();
      markUserAccidentals(scoreRelStaff, part->nstaves(), key, measure, alterMap);

      // multi-measure rest handling
      if (getAndDecMultiMeasureRestCount() == 0) {
            // measure is first measure after a multi-measure rest
            measure->setBreakMultiMeasureRest(true);
            }

      Q_ASSERT(_e.isEndElement() && _e.name() == "measure");
      }

//---------------------------------------------------------
//   attributes
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes node.
 */

/* Notes:
 * Number of staves has already been set in pass 1
 * MusicXML order is key, time, clef
 * -> check if it is necessary to insert them in order
 */

void MusicXMLParserPass2::attributes(const QString& partId, Measure* measure, const int tick)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "attributes");

      while (_e.readNextStartElement()) {
            if (_e.name() == "clef")
                  clef(partId, measure, tick);
            else if (_e.name() == "divisions")
                  divisions();
            else if (_e.name() == "key")
                  key(partId, measure, tick);
            else if (_e.name() == "measure-style")
                  measureStyle(measure);
            else if (_e.name() == "staff-details")
                  staffDetails(partId);
            else if (_e.name() == "time")
                  time(partId, measure, tick);
            else if (_e.name() == "transpose")
                  transpose(partId);
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   setStaffLines
//---------------------------------------------------------

/**
 Set stafflines and barline span for a single staff
 */

static void setStaffLines(Score* score, int staffIdx, int stafflines)
      {
      score->staff(staffIdx)->setLines(stafflines);
      score->staff(staffIdx)->setBarLineTo((stafflines - 1) * 2);
      }

//---------------------------------------------------------
//   staffDetails
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/staff-details node.
 */

void MusicXMLParserPass2::staffDetails(const QString& partId)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "staff-details");
      //logDebugTrace("MusicXMLParserPass2::staffDetails");

      Part* part = _pass1.getPart(partId);
      Q_ASSERT(part);
      int staves = part->nstaves();

      QString number = _e.attributes().value("number").toString();
      int n = 1;  // default
      if (number != "") {
            n = number.toInt();
            if (n <= 0 || n > staves) {
                  _logger->logError(QString("invalid staff-details number %1").arg(number), &_e);
                  n = 1;
                  }
            }
      n--;         // make zero-based

      int staffIdx = _score->staffIdx(part) + n;

      StringData* t = 0;
      if (_score->staff(staffIdx)->isTabStaff()) {
            t = new StringData;
            t->setFrets(25);  // sensible default
            }

      int staffLines = 0;
      while (_e.readNextStartElement()) {
            if (_e.name() == "staff-lines") {
                  // save staff lines for later
                  staffLines = _e.readElementText().toInt();
                  // for a TAB staff also resize the string table and init with zeroes
                  if (t) {
                        if (0 < staffLines)
                              t->stringList() = QVector<instrString>(staffLines).toList();
                        else
                              _logger->logError(QString("illegal staff-lines %1").arg(staffLines), &_e);
                        }
                  }
            else if (_e.name() == "staff-tuning")
                  staffTuning(t);
            else
                  skipLogCurrElem();
            }

      if (staffLines > 0) {
            setStaffLines(_score, staffIdx, staffLines);
            }

      if (t) {
            Instrument* i = part->instrument();
            i->setStringData(*t);
            }
      }
//---------------------------------------------------------
//   staffTuning
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/staff-details/staff-tuning node.
 */

void MusicXMLParserPass2::staffTuning(StringData* t)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "staff-tuning");
      //logDebugTrace("MusicXMLParserPass2::staffTuning");

      // ignore <staff-tuning> if not a TAB staff
      if (!t) {
            _logger->logError("<staff-tuning> on non-TAB staff", &_e);
            skipLogCurrElem();
            return;
            }

      int line   = _e.attributes().value("line").toInt();
      int step   = 0;
      int alter  = 0;
      int octave = 0;
      while (_e.readNextStartElement()) {
            if (_e.name() == "tuning-alter")
                  alter = _e.readElementText().toInt();
            else if (_e.name() == "tuning-octave")
                  octave = _e.readElementText().toInt();
            else if (_e.name() == "tuning-step") {
                  QString strStep = _e.readElementText();
                  int pos = QString("CDEFGAB").indexOf(strStep);
                  if (strStep.size() == 1 && pos >=0 && pos < 7)
                        step = pos;
                  else
                        _logger->logError(QString("invalid step '%1'").arg(strStep), &_e);
                  }
            else
                  skipLogCurrElem();
            }

      if (0 < line && line <= t->stringList().size()) {
            int pitch = MusicXMLStepAltOct2Pitch(step, alter, octave);
            if (pitch >= 0)
                  t->stringList()[line - 1].pitch = pitch;
            else
                  _logger->logError(QString("invalid string %1 tuning step/alter/oct %2/%3/%4")
                                    .arg(line).arg(step).arg(alter).arg(octave),
                                    &_e);
            }
      }

//---------------------------------------------------------
//   measureStyle
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/measure-style node.
 Initializes the "in multi-measure rest" state
 */

void MusicXMLParserPass2::measureStyle(Measure* measure)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "measure-style");

      while (_e.readNextStartElement()) {
            if (_e.name() == "multiple-rest") {
                  int multipleRest = _e.readElementText().toInt();
                  if (multipleRest > 1) {
                        _multiMeasureRestCount = multipleRest;
                        _score->style()->set(StyleIdx::createMultiMeasureRests, true);
                        measure->setBreakMultiMeasureRest(true);
                        }
                  else
                        _logger->logError(QString("multiple-rest %1 not supported").arg(multipleRest), &_e);
                  }
            else
                  skipLogCurrElem();
            }
      }


//---------------------------------------------------------
//   print
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/print node.
 */

void MusicXMLParserPass2::print(Measure* measure)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "print");

      bool newSystem = _e.attributes().value("new-system") == "yes";
      bool newPage   = _e.attributes().value("new-page") == "yes";
      int blankPage = _e.attributes().value("blank-page").toInt();
      //
      // in MScore the break happens _after_ the marked measure:
      //
      MeasureBase* pm = measure->prevMeasure();        // We insert VBox only for title, no HBox for the moment
      if (pm == 0) {
            _logger->logDebugInfo("break on first measure", &_e);
            if (blankPage == 1) {       // blank title page, insert a VBOX if needed
                  pm = measure->prev();
                  if (pm == 0) {
                        pm = _score->insertMeasure(Element::Type::VBOX, measure);
                        }
                  }
            }
      if (pm) {
            if (preferences.musicxmlImportBreaks && (newSystem || newPage)) {
                  LayoutBreak* lb = new LayoutBreak(_score);
                  lb->setLayoutBreakType(newSystem ? LayoutBreak::Type::LINE : LayoutBreak::Type::PAGE);
                  pm->add(lb);
                  }
            }

      while (_e.readNextStartElement()) {
            skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   direction
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction node.
 */

void MusicXMLParserDirection::direction(const QString& partId,
                                        Measure* measure,
                                        const int tick,
                                        MusicXmlSpannerMap& spanners)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "direction");
      //qDebug("direction tick %d", tick);

      QString placement = _e.attributes().value("placement").toString();
      int track = _pass1.trackForPart(partId);
      //qDebug("direction track %d", track);
      QList<MusicXmlSpannerDesc> starts;
      QList<MusicXmlSpannerDesc> stops;

      // note: file order is direction-type first, then staff
      // this means staff is still unknown when direction-type is handled
      // easiest solution is to put spanners on a stop and start list
      // and handle these after the while loop

      // note that placement is a <direction> attribute (which is currently supported by MS)
      // but the <direction-type> children also have formatting attributes
      // (currently NOT supported by MS, at least not for spanners when <direction> children)

      while (_e.readNextStartElement()) {
            if (_e.name() == "direction-type")
                  directionType(starts, stops);
            else if (_e.name() == "staff") {
                  int nstaves = _pass1.getPart(partId)->nstaves();
                  QString strStaff = _e.readElementText();
                  int staff = strStaff.toInt();
                  if (0 < staff && staff <= nstaves)
                        track += (staff - 1) * VOICES;
                  else
                        _logger->logError(QString("invalid staff %1").arg(strStaff), &_e);
                  }
            else if (_e.name() == "sound")
                  sound();
            else
                  skipLogCurrElem();
            }

      handleRepeats(measure, track);

      // fix for Sibelius 7.1.3 (direct export) which creates metronomes without <sound tempo="..."/>:
      // if necessary, use the value calculated by metronome()
      // note: no floating point comparisons with 0 ...
      if (_tpoSound < 0.1 && _tpoMetro > 0.1)
            _tpoSound = _tpoMetro;

      //qDebug("words '%s' rehearsal '%s' metro '%s' tpo %g",
      //       qPrintable(_wordsText), qPrintable(_rehearsalText), qPrintable(_metroText), _tpoSound);

      // create text if any text was found

      if (_wordsText != "" || _rehearsalText != "" || _metroText != "") {
            Text* t = 0;
            if (_tpoSound > 0.1) {
                  _tpoSound /= 60;
                  t = new TempoText(_score);
                  t->setXmlText(_wordsText + _metroText);
                  ((TempoText*) t)->setTempo(_tpoSound);
                  ((TempoText*) t)->setFollowText(true);
                  _score->setTempo(tick, _tpoSound);
                  }
            else {
                  if (_wordsText != "" || _metroText != "") {
                        t = new StaffText(_score);
                        t->setXmlText(_wordsText + _metroText);
                        }
                  else {
                        t = new RehearsalMark(_score);
                        if (!_rehearsalText.contains("<b>"))
                              _rehearsalText = "<b></b>" + _rehearsalText;  // explicitly turn bold off
                        t->setXmlText(_rehearsalText);
                        if (!_hasDefaultY)
                              t->setPlacement(Element::Placement::ABOVE);  // crude way to force placement TODO improve ?
                        }
                  }

            if (_enclosure == "circle") {
                  t->textStyle().setHasFrame(true);
                  t->textStyle().setCircle(true);
                  }
            else if (_enclosure == "none") {
                  t->textStyle().setHasFrame(false);
                  }
            else if (_enclosure == "rectangle") {
                  t->textStyle().setHasFrame(true);
                  t->textStyle().setFrameRound(0);
                  }

            if (_hasDefaultY) t->textStyle().setYoff(_defaultY);
            addElemOffset(t, track, placement, measure, tick);
            }
      else if (_tpoSound > 0) {
            double tpo = _tpoSound / 60;
            TempoText* t = new TempoText(_score);
            t->setXmlText(QString("%1 = %2").arg(TempoText::duration2tempoTextString(TDuration(TDuration::DurationType::V_QUARTER))).arg(_tpoSound));
            t->setTempo(tpo);
            t->setFollowText(true);

            _score->setTempo(tick, tpo);

            addElemOffset(t, track, placement, measure, tick);
            }

      // do dynamics
      // LVIFIX: check import/export of <other-dynamics>unknown_text</...>
      for (QStringList::Iterator it = _dynamicsList.begin(); it != _dynamicsList.end(); ++it ) {
            Dynamic* dyn = new Dynamic(_score);
            dyn->setDynamicType(*it);
            if (!_dynaVelocity.isEmpty()) {
                  int dynaValue = round(_dynaVelocity.toDouble() * 0.9);
                  if (dynaValue > 127)
                        dynaValue = 127;
                  else if (dynaValue < 0)
                        dynaValue = 0;
                  dyn->setVelocity( dynaValue );
                  }
            if (_hasDefaultY) dyn->textStyle().setYoff(_defaultY);
            addElemOffset(dyn, track, placement, measure, tick);
            }

      // handle the elems
      foreach( auto elem, _elems) {
            // TODO (?) if (_hasDefaultY) elem->setYoff(_defaultY);
            addElemOffset(elem, track, placement, measure, tick);
            }

      // handle the spanner stops first
      foreach (auto desc, stops) {
            SLine* sp = _pass2.getSpanner(desc);
            if (sp) {
                  handleSpannerStop(sp, track, tick, spanners);
                  _pass2.clearSpanner(desc);
                  }
            else
                  _logger->logError("spanner stop without spanner start", &_e);
            }

      // then handle the spanner starts
      foreach (auto desc, starts) {
            SLine* sp = _pass2.getSpanner(desc);
            if (!sp) {
                  _pass2.addSpanner(desc);
                  handleSpannerStart(desc.sp, track, placement, tick, spanners);
                  }
            else
                  _logger->logError("spanner already started", &_e);
            }

      Q_ASSERT(_e.isEndElement() && _e.name() == "direction");
      }

//---------------------------------------------------------
//   directionType
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type node.
 */

void MusicXMLParserDirection::directionType(QList<MusicXmlSpannerDesc>& starts,
                                            QList<MusicXmlSpannerDesc>& stops)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "direction-type");

      while (_e.readNextStartElement()) {
            _defaultY = _e.attributes().value("default-y").toDouble(&_hasDefaultY) * -0.1;
            QString number = _e.attributes().value("number").toString();
            int n = 0;
            if (number != "") {
                  n = number.toInt();
                  if (n <= 0)
                        _logger->logError(QString("invalid number %1").arg(number), &_e);
                  else
                        n--;  // make zero-based
                  }
            QString type = _e.attributes().value("type").toString();
            if  (_e.name() == "metronome")
                  _metroText = metronome(_tpoMetro);
            else if (_e.name() == "words") {
                  _enclosure      = _e.attributes().value("enclosure").toString();
                  _wordsText += nextPartOfFormattedString(_e);
                  }
            else if (_e.name() == "rehearsal") {
                  _enclosure      = _e.attributes().value("enclosure").toString();
                  if (_enclosure == "")
                        _enclosure = "square";  // note different default
                  _rehearsalText += nextPartOfFormattedString(_e);
                  }
            else if (_e.name() == "pedal")
                  pedal(type, n, starts, stops);
            else if (_e.name() == "octave-shift")
                  octaveShift(type, n, starts, stops);
            else if (_e.name() == "dynamics")
                  dynamics();
            else if (_e.name() == "bracket")
                  bracket(type, n, starts, stops);
            else if (_e.name() == "dashes")
                  dashes(type, n, starts, stops);
            else if (_e.name() == "wedge")
                  wedge(type, n, starts, stops);
            else if (_e.name() == "coda") {
                  _coda = true;
                  _e.skipCurrentElement();
                  }
            else if (_e.name() == "segno") {
                  _segno = true;
                  _e.skipCurrentElement();
                  }
            else
                  skipLogCurrElem();
            }

      Q_ASSERT(_e.isEndElement() && _e.name() == "direction-type");
      }

//---------------------------------------------------------
//   sound
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/sound node.
 */

void MusicXMLParserDirection::sound()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "sound");

      _sndCapo = _e.attributes().value("capo").toString();
      _sndCoda = _e.attributes().value("coda").toString();
      _sndDacapo = _e.attributes().value("dacapo").toString();
      _sndDalsegno = _e.attributes().value("dalsegno").toString();
      _sndFine = _e.attributes().value("fine").toString();
      _sndSegno = _e.attributes().value("segno").toString();
      _tpoSound = _e.attributes().value("tempo").toDouble();
      _dynaVelocity = _e.attributes().value("dynamics").toString();

      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   dynamics
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/dynamics node.
 */

void MusicXMLParserDirection::dynamics()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "dynamics");

      while (_e.readNextStartElement()) {
            if (_e.name() == "other-dynamics")
                  _dynamicsList.push_back(_e.readElementText());
            else {
                  _dynamicsList.push_back(_e.name().toString());
                  _e.skipCurrentElement();
                  }
            }
      }

//---------------------------------------------------------
//   matchRepeat
//---------------------------------------------------------

/**
 Do a wild-card match with known repeat texts.
 */

static QString matchRepeat(const QString& lowerTxt)
      {
      QString repeat;
      QRegExp daCapo("d\\.? *c\\.?|da *capo");
      QRegExp daCapoAlFine("d\\.? *c\\.? *al *fine|da *capo *al *fine");
      QRegExp daCapoAlCoda("d\\.? *c\\.? *al *coda|da *capo *al *coda");
      QRegExp dalSegno("d\\.? *s\\.?|d[ae]l *segno");
      QRegExp dalSegnoAlFine("d\\.? *s\\.? *al *fine|d[ae]l *segno *al *fine");
      QRegExp dalSegnoAlCoda("d\\.? *s\\.? *al *coda|d[ae]l *segno *al *coda");
      QRegExp fine("fine");
      QRegExp toCoda("to *coda");
      if (daCapo.exactMatch(lowerTxt)) repeat = "daCapo";
      if (daCapoAlFine.exactMatch(lowerTxt)) repeat = "daCapoAlFine";
      if (daCapoAlCoda.exactMatch(lowerTxt)) repeat = "daCapoAlCoda";
      if (dalSegno.exactMatch(lowerTxt)) repeat = "dalSegno";
      if (dalSegnoAlFine.exactMatch(lowerTxt)) repeat = "dalSegnoAlFine";
      if (dalSegnoAlCoda.exactMatch(lowerTxt)) repeat = "dalSegnoAlCoda";
      if (fine.exactMatch(lowerTxt)) repeat = "fine";
      if (toCoda.exactMatch(lowerTxt)) repeat = "toCoda";
      return repeat;
      }

//---------------------------------------------------------
//   findJump
//---------------------------------------------------------

/**
 Try to find a Jump in \a repeat.
 */

static Jump* findJump(const QString& repeat, Score* score)
      {
      Jump* jp = 0;
      if (repeat == "daCapo") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DC);
            }
      else if (repeat == "daCapoAlCoda") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DC_AL_CODA);
            }
      else if (repeat == "daCapoAlFine") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DC_AL_FINE);
            }
      else if (repeat == "dalSegno") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DS);
            }
      else if (repeat == "dalSegnoAlCoda") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DS_AL_CODA);
            }
      else if (repeat == "dalSegnoAlFine") {
            jp = new Jump(score);
            jp->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            jp->setJumpType(Jump::Type::DS_AL_FINE);
            }
      return jp;
      }

//---------------------------------------------------------
//   findMarker
//---------------------------------------------------------

/**
 Try to find a Marker in \a repeat.
 */

static Marker* findMarker(const QString& repeat, Score* score)
      {
      Marker* m = 0;
      if (repeat == "segno") {
            m = new Marker(score);
            // note: Marker::read() also contains code to set text style based on type
            // avoid duplicated code
            m->setTextStyleType(TextStyleType::REPEAT_LEFT);
            // apparently this MUST be after setTextStyle
            m->setMarkerType(Marker::Type::SEGNO);
            }
      else if (repeat == "coda") {
            m = new Marker(score);
            m->setTextStyleType(TextStyleType::REPEAT_LEFT);
            m->setMarkerType(Marker::Type::CODA);
            }
      else if (repeat == "fine") {
            m = new Marker(score);
            m->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            m->setMarkerType(Marker::Type::FINE);
            }
      else if (repeat == "toCoda") {
            m = new Marker(score);
            m->setTextStyleType(TextStyleType::REPEAT_RIGHT);
            m->setMarkerType(Marker::Type::TOCODA);
            }
      return m;
      }

//---------------------------------------------------------
//   handleRepeats
//---------------------------------------------------------

void MusicXMLParserDirection::handleRepeats(Measure* measure, const int track)
      {
      // Try to recognize the various repeats
      QString repeat = "";
      // Easy cases first
      if (_coda) repeat = "coda";
      if (_segno) repeat = "segno";
      // As sound may be missing, next do a wild-card match with known repeat texts
      QString txt = MScoreTextToMXML::toPlainText(_wordsText.toLower());
      if (repeat == "") repeat = matchRepeat(txt.toLower());
      // If that did not work, try to recognize a sound attribute
      if (repeat == "" && _sndCoda != "") repeat = "coda";
      if (repeat == "" && _sndDacapo != "") repeat = "daCapo";
      if (repeat == "" && _sndDalsegno != "") repeat = "dalSegno";
      if (repeat == "" && _sndFine != "") repeat = "fine";
      if (repeat == "" && _sndSegno != "") repeat = "segno";
      // If a repeat was found, assume words is no longer needed
      if (repeat != "") _wordsText = "";

      /*
       qDebug(" txt=%s repeat=%s",
       qPrintable(txt),
       qPrintable(repeat)
       );
       */

      if (repeat != "") {
            if (Jump* jp = findJump(repeat, _score)) {
                  jp->setTrack(track);
                  qDebug("jumpsMarkers adding jm %p meas %p",jp, measure);
                  // TODO jumpsMarkers.append(JumpMarkerDesc(jp, measure));
                  measure->add(jp);
                  }
            if (Marker* m = findMarker(repeat, _score)) {
                  m->setTrack(track);
                  qDebug("jumpsMarkers adding jm %p meas %p",m, measure);
                  // TODO jumpsMarkers.append(JumpMarkerDesc(m, measure));
                  measure->add(m);
                  }
            }
      }

//---------------------------------------------------------
//   bracket
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/bracket node.
 */

void MusicXMLParserDirection::bracket(const QString& type, const int number,
                                      QList<MusicXmlSpannerDesc>& starts, QList<MusicXmlSpannerDesc>& stops)
      {
      QStringRef lineEnd = _e.attributes().value("line-end");
      QStringRef lineType = _e.attributes().value("line-type");
      if (type == "start") {
            TextLine* b = new TextLine(_score);
            // if (placement == "") placement = "above";  // TODO ? set default

            b->setBeginHook(lineEnd != "none");
            if (lineEnd == "up")
                  b->setBeginHookHeight(-1 * b->beginHookHeight());

            // hack: combine with a previous words element
            if (!_wordsText.isEmpty()) {
                  // TextLine supports only limited formatting, remove all (compatible with 1.3)
                  b->setBeginText(MScoreTextToMXML::toPlainText(_wordsText), TextStyleType::TEXTLINE);
                  _wordsText = "";
                  }

            if (lineType == "solid")
                  b->setLineStyle(Qt::SolidLine);
            else if (lineType == "dashed")
                  b->setLineStyle(Qt::DashLine);
            else if (lineType == "dotted")
                  b->setLineStyle(Qt::DotLine);
            else
                  _logger->logError(QString("unsupported line-type: %1").arg(lineType.toString()), &_e);
            starts.append(MusicXmlSpannerDesc(b, Element::Type::TEXTLINE, number));
            }
      else if (type == "stop") {
            TextLine* b = static_cast<TextLine*>(_pass2.getSpanner(MusicXmlSpannerDesc(Element::Type::TEXTLINE, number)));
            if (b) {
                  b->setEndHook(lineEnd != "none");
                  if (lineEnd == "up")
                        b->setEndHookHeight(-1 * b->endHookHeight());
                  }
            stops.append(MusicXmlSpannerDesc(Element::Type::TEXTLINE, number));
            }
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   dashes
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/dashes node.
 */

void MusicXMLParserDirection::dashes(const QString& type, const int number,
                                     QList<MusicXmlSpannerDesc>& starts, QList<MusicXmlSpannerDesc>& stops)
      {
      if (type == "start") {
            TextLine* b = new TextLine(_score);
            // if (placement == "") placement = "above";  // TODO ? set default

            // hack: combine with a previous words element
            if (!_wordsText.isEmpty()) {
                  // TextLine supports only limited formatting, remove all (compatible with 1.3)
                  b->setBeginText(MScoreTextToMXML::toPlainText(_wordsText), TextStyleType::TEXTLINE);
                  _wordsText = "";
                  }

            b->setBeginHook(false);
            b->setEndHook(false);
            b->setLineStyle(Qt::DashLine);
            // TODO brackets and dashes now share the same storage
            // because they both use Element::Type::TEXTLINE
            // use mxml specific type instead
            starts.append(MusicXmlSpannerDesc(b, Element::Type::TEXTLINE, number));
            }
      else if (type == "stop")
            stops.append(MusicXmlSpannerDesc(Element::Type::TEXTLINE, number));
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   octaveShift
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/octave-shift node.
 */

void MusicXMLParserDirection::octaveShift(const QString& type, const int number,
                                          QList<MusicXmlSpannerDesc>& starts, QList<MusicXmlSpannerDesc>& stops)
      {
      if (type == "up" || type == "down") {
            int ottavasize = _e.attributes().value("size").toInt();
            if (!(ottavasize == 8 || ottavasize == 15)) {
                  _logger->logError(QString("unknown octave-shift size %1").arg(ottavasize), &_e);
                  }
            else {
                  Ottava* o = new Ottava(_score);

                  // if (placement == "") placement = "above";  // TODO ? set default

                  if (type == "down" && ottavasize ==  8) o->setOttavaType(Ottava::Type::OTTAVA_8VA);
                  if (type == "down" && ottavasize == 15) o->setOttavaType(Ottava::Type::OTTAVA_15MA);
                  if (type ==   "up" && ottavasize ==  8) o->setOttavaType(Ottava::Type::OTTAVA_8VB);
                  if (type ==   "up" && ottavasize == 15) o->setOttavaType(Ottava::Type::OTTAVA_15MB);

                  starts.append(MusicXmlSpannerDesc(o, Element::Type::OTTAVA, number));
                  }
            }
      else if (type == "stop")
            stops.append(MusicXmlSpannerDesc(Element::Type::OTTAVA, number));
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   pedal
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/pedal node.
 */

void MusicXMLParserDirection::pedal(const QString& type, const int /* number */,
                                    QList<MusicXmlSpannerDesc>& starts,
                                    QList<MusicXmlSpannerDesc>& stops)
      {
      QStringRef line = _e.attributes().value("line");
      QString sign = _e.attributes().value("sign").toString();
      if (line != "yes" && sign == "") sign = "yes";       // MusicXML 2.0 compatibility
      if (line == "yes" && sign == "") sign = "no";        // MusicXML 2.0 compatibility
      if (line == "yes") {
            if (type == "start") {
                  Pedal* p = new Pedal(_score);
                  if (sign == "yes")
                        p->setBeginText("<sym>keyboardPedalPed</sym>");
                  else
                        p->setBeginHook(true);
                  p->setEndHook(true);
                  // if (placement == "") placement = "below";  // TODO ? set default
                  starts.append(MusicXmlSpannerDesc(p, Element::Type::PEDAL, 0));
                  }
            else if (type == "stop")
                  stops.append(MusicXmlSpannerDesc(Element::Type::PEDAL, 0));
            else if (type == "change") {
#if 0
                  TODO
                  // pedal change is implemented as two separate pedals
                  // first stop the first one
                  if (pedal) {
                        pedal->setEndHookType(HookType::HOOK_45);
                        handleSpannerStop(pedal, "pedal", track, tick, spanners);
                        pedalContinue = pedal; // mark for later fixup
                        pedal = 0;
                        }
                  // then start a new one
                  pedal = static_cast<Pedal*>(checkSpannerOverlap(pedal, new Pedal(score), "pedal"));
                  pedal->setBeginHook(true);
                  pedal->setBeginHookType(HookType::HOOK_45);
                  pedal->setEndHook(true);
                  if (placement == "") placement = "below";
                  handleSpannerStart(pedal, "pedal", track, placement, tick, spanners);
#endif
                  }
            else if (type == "continue") {
                  // ignore
                  }
            else
                  qDebug("unknown pedal type %s", qPrintable(type));
            }
      else {
            // TBD: what happens when an unknown pedal type is found ?
            Symbol* s = new Symbol(_score);
            s->setAlign(AlignmentFlags::LEFT | AlignmentFlags::BASELINE);
            s->setOffsetType(OffsetType::SPATIUM);
            if (type == "start")
                  s->setSym(SymId::keyboardPedalPed);
            else if (type == "stop")
                  s->setSym(SymId::keyboardPedalUp);
            else
                  _logger->logError(QString("unknown pedal type %1").arg(type), &_e);
            _elems.append(s);
            }

      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   wedge
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/wedge node.
 */

void MusicXMLParserDirection::wedge(const QString& type, const int number,
                                    QList<MusicXmlSpannerDesc>& starts, QList<MusicXmlSpannerDesc>& stops)
      {
      QStringRef niente = _e.attributes().value("niente");
      if (type == "crescendo" || type == "diminuendo") {
            Hairpin* h = new Hairpin(_score);
            h->setHairpinType(type == "crescendo"
                              ? Hairpin::Type::CRESCENDO : Hairpin::Type::DECRESCENDO);
            if (niente == "yes")
                  h->setHairpinCircledTip(true);
            starts.append(MusicXmlSpannerDesc(h, Element::Type::HAIRPIN, number));
            }
      else if (type == "stop") {
            Hairpin* h = static_cast<Hairpin*>(_pass2.getSpanner(MusicXmlSpannerDesc(Element::Type::HAIRPIN, number)));
            if (niente == "yes")
                  h->setHairpinCircledTip(true);
            stops.append(MusicXmlSpannerDesc(Element::Type::HAIRPIN, number));
            }
      _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   addSpanner
//---------------------------------------------------------

void MusicXMLParserPass2::addSpanner(const MusicXmlSpannerDesc& d)
      {
      if (d.tp == Element::Type::HAIRPIN && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            _hairpins[d.nr] = d.sp;
      else if (d.tp == Element::Type::OTTAVA && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            _ottavas[d.nr] = d.sp;
      else if (d.tp == Element::Type::PEDAL && 0 == d.nr)
            _pedal = d.sp;
      // TODO: check MAX_BRACKETS vs MAX_NUMBER_LEVEL
      else if (d.tp == Element::Type::TEXTLINE && 0 <= d.nr && d.nr < MAX_BRACKETS)
            _brackets[d.nr] = d.sp;
      }

//---------------------------------------------------------
//   getSpanner
//---------------------------------------------------------

SLine* MusicXMLParserPass2::getSpanner(const MusicXmlSpannerDesc& d)
      {
      if (d.tp == Element::Type::HAIRPIN && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            return _hairpins[d.nr];
      else if (d.tp == Element::Type::OTTAVA && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            return _ottavas[d.nr];
      else if (d.tp == Element::Type::PEDAL && 0 == d.nr)
            return _pedal;
      // TODO: check MAX_BRACKETS vs MAX_NUMBER_LEVEL
      else if (d.tp == Element::Type::TEXTLINE && 0 <= d.nr && d.nr < MAX_BRACKETS)
            return _brackets[d.nr];
      return 0;
      }

//---------------------------------------------------------
//   clearSpanner
//---------------------------------------------------------

void MusicXMLParserPass2::clearSpanner(const MusicXmlSpannerDesc& d)
      {
      if (d.tp == Element::Type::HAIRPIN && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            _hairpins[d.nr] = 0;
      else if (d.tp == Element::Type::OTTAVA && 0 <= d.nr && d.nr < MAX_NUMBER_LEVEL)
            _ottavas[d.nr] = 0;
      else if (d.tp == Element::Type::PEDAL && 0 == d.nr)
            _pedal = 0;
      // TODO: check MAX_BRACKETS vs MAX_NUMBER_LEVEL
      else if (d.tp == Element::Type::TEXTLINE && 0 <= d.nr && d.nr < MAX_BRACKETS)
            _brackets[d.nr] = 0;
      }

//---------------------------------------------------------
//   metronome
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/direction/direction-type/metronome node.
 Convert to text and set r to calculated tempo.
 */

QString MusicXMLParserDirection::metronome(double& r)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "metronome");

      r = 0;
      QString tempoText;
      QString perMinute;
      bool parenth = _e.attributes().value("parentheses") == "yes";

      if (parenth)
            tempoText += "(";

      TDuration dur1;
      TDuration dur2;

      while (_e.readNextStartElement()) {
            if (_e.name() == "metronome-note" || _e.name() == "metronome-relation") {
                  skipLogCurrElem();
                  continue;
                  }
            QString txt = _e.readElementText();
            if (_e.name() == "beat-unit") {
                  // set first dur that is still invalid
                  if (!dur1.isValid()) dur1.setType(txt);
                  else if (!dur2.isValid()) dur2.setType(txt);
                  }
            else if (_e.name() == "beat-unit-dot") {
                  if (dur2.isValid()) dur2.setDots(1);
                  else if (dur1.isValid()) dur1.setDots(1);
                  }
            else if (_e.name() == "per-minute")
                  perMinute = txt;
            else
                  skipLogCurrElem();
            }

      if (dur1.isValid())
            tempoText += TempoText::duration2tempoTextString(dur1);
      if (dur2.isValid()) {
            tempoText += " = ";
            tempoText += TempoText::duration2tempoTextString(dur2);
            }
      else if (perMinute != "") {
            tempoText += " = ";
            tempoText += perMinute;
            }
      if (dur1.isValid() && !dur2.isValid() && perMinute != "") {
            bool ok;
            double d = perMinute.toDouble(&ok);
            if (ok) {
                  // convert fraction to beats per minute
                  r = 4 * dur1.fraction().numerator() * d / dur1.fraction().denominator();
                  }
            }

      if (parenth)
            tempoText += ")";

      return tempoText;
      }

//---------------------------------------------------------
//   determineBarLineType
//---------------------------------------------------------

static bool determineBarLineType(const QString& barStyle, const QString& repeat,
                                 BarLineType& type, bool& visible)
      {
      // set defaults
      type = BarLineType::NORMAL;
      visible = true;

      if (barStyle == "light-heavy" && repeat == "backward")
            type = BarLineType::END_REPEAT;
      else if (barStyle == "heavy-light" && repeat == "forward")
            type = BarLineType::START_REPEAT;
      else if (barStyle == "light-heavy" && repeat.isEmpty())
            type = BarLineType::END;
      else if (barStyle == "regular")
            type = BarLineType::NORMAL;
      else if (barStyle == "dashed")
            type = BarLineType::BROKEN;
      else if (barStyle == "dotted")
            type = BarLineType::DOTTED;
      else if (barStyle == "light-light")
            type = BarLineType::DOUBLE;
      /*
       else if (barStyle == "heavy-light")
       ;
       else if (barStyle == "heavy-heavy")
       ;
       */
      else if (barStyle == "none") {
            type = BarLineType::NORMAL;
            visible = false;
            }
      else if (barStyle == "") {
            if (repeat == "backward")
                  type = BarLineType::END_REPEAT;
            else if (repeat == "forward")
                  type = BarLineType::START_REPEAT;
            else {
                  qDebug("empty bar type");       // TODO
                  return false;
                  }
            }
      else if (barStyle == "tick") {
            }
      else if (barStyle == "short") {
            }
      else {
            qDebug("unsupported bar type <%s>", qPrintable(barStyle));       // TODO
            return false;
            }

      return true;
      }

//---------------------------------------------------------
//   barline
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/barline node.
 */

void MusicXMLParserPass2::barline(const QString& partId, Measure* measure)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "barline");

      QString loc = _e.attributes().value("location").toString();
      if (loc == "")
            loc = "right";
      QString barStyle;
      QString endingNumber;
      QString endingType;
      QString endingText;
      QString repeat;
      QString count;

      while (_e.readNextStartElement()) {
            if (_e.name() == "bar-style")
                  barStyle = _e.readElementText();
            else if (_e.name() == "ending") {
                  endingNumber = _e.attributes().value("number").toString();
                  endingType   = _e.attributes().value("type").toString();
                  endingText = _e.readElementText();
                  }
            else if (_e.name() == "repeat") {
                  repeat = _e.attributes().value("direction").toString();
                  count = _e.attributes().value("times").toString();
                  if (count.isEmpty()) {
                        count = "2";
                        }
                  measure->setRepeatCount(count.toInt());
                  _e.skipCurrentElement();
                  }
            else
                  skipLogCurrElem();
            }

      BarLineType type = BarLineType::NORMAL;
      bool visible = true;
      if (determineBarLineType(barStyle, repeat, type, visible)) {
            if (type == BarLineType::START_REPEAT) {
                  // combine start_repeat flag with current state initialized during measure parsing
                  measure->setRepeatFlag(Repeat::START);
                  }
            else if (type == BarLineType::END_REPEAT) {
                  // combine end_repeat flag with current state initialized during measure parsing
                  measure->setRepeatFlag(Repeat::END);
                  }
            else {
                  if (loc == "right")
                        measure->setEndBarLineType(type, false, visible);
                  else if (measure->prevMeasure())
                        measure->prevMeasure()->setEndBarLineType(type, false, visible);
                  }
            }

      doEnding(partId, measure, endingNumber, endingType, endingText);
      }

//---------------------------------------------------------
//   doEnding
//---------------------------------------------------------

void MusicXMLParserPass2::doEnding(const QString& partId, Measure* measure,
                                   const QString& number, const QString& type, const QString& text)
      {
      if (!(number.isEmpty() && type.isEmpty())) {
            if (number.isEmpty())
                  _logger->logError("empty ending number", &_e);
            else if (type.isEmpty())
                  _logger->logError("empty ending type", &_e);
            else {
                  QStringList sl = number.split(",", QString::SkipEmptyParts);
                  QList<int> iEndingNumbers;
                  bool unsupported = false;
                  foreach(const QString &s, sl) {
                        int iEndingNumber = s.toInt();
                        if (iEndingNumber <= 0) {
                              unsupported = true;
                              break;
                              }
                        iEndingNumbers.append(iEndingNumber);
                        }

                  if (unsupported)
                        _logger->logError(QString("unsupported ending number '%1'").arg(number), &_e);
                  else {
                        if (type == "start") {
                              Volta* volta = new Volta(_score);
                              volta->setTrack(_pass1.trackForPart(partId));
                              volta->setText(text.isEmpty() ? number : text);
                              // LVIFIX TODO also support endings "1 - 3"
                              volta->endings().clear();
                              volta->endings().append(iEndingNumbers);
                              volta->setTick(measure->tick());
                              _score->addElement(volta);
                              _lastVolta = volta;
                              }
                        else if (type == "stop") {
                              if (_lastVolta) {
                                    _lastVolta->setVoltaType(Volta::Type::CLOSED);
                                    _lastVolta->setTick2(measure->tick() + measure->ticks());
                                    _lastVolta = 0;
                                    }
                              else
                                    _logger->logError("ending stop without start", &_e);
                              }
                        else if (type == "discontinue") {
                              if (_lastVolta) {
                                    _lastVolta->setVoltaType(Volta::Type::OPEN);
                                    _lastVolta->setTick2(measure->tick() + measure->ticks());
                                    _lastVolta = 0;
                                    }
                              else
                                    _logger->logError("ending discontinue without start", &_e);
                              }
                        else
                              _logger->logError(QString("unsupported ending type '%1'").arg(type), &_e);
                        }
                  }
            }
      }

//---------------------------------------------------------
//   addSymToSig
//---------------------------------------------------------

/**
 Add a symbol defined as key-step \a step , -alter \a alter and -accidental \a accid to \a sig.
 */

static void addSymToSig(KeySigEvent& sig, const QString& step, const QString& alter, const QString& accid)
      {
      //qDebug("addSymToSig(step '%s' alt '%s' acc '%s')",
      //       qPrintable(step), qPrintable(alter), qPrintable(accid));

      SymId id = mxmlString2accSymId(accid);
      if (id == SymId::noSym) {
            bool ok;
            double d;
            d = alter.toDouble(&ok);
            AccidentalType accTpAlter = ok ? microtonalGuess(d) : AccidentalType::NONE;
            id = mxmlString2accSymId(accidentalType2MxmlString(accTpAlter));
            }

      if (step.size() == 1 && id != SymId::noSym) {
            const QString table = "FEDCBAG";
            const int line = table.indexOf(step);
            // no auto layout for custom keysig, calculate xpos
            // TODO: use symbol width ?
            const qreal spread = 1.4; // assumed glyph width in space
            const qreal x = sig.keySymbols().size() * spread;
            if (line >= 0) {
                  KeySym ks;
                  ks.sym  = id;
                  ks.spos = QPointF(x, qreal(line) * 0.5);
                  sig.keySymbols().append(ks);
                  sig.setCustom(true);
                  }
            }
      }

//---------------------------------------------------------
//   addKey
//---------------------------------------------------------

/**
 Add a KeySigEvent to the score.
 */

static void addKey(const KeySigEvent key, const bool printObj, Score* score, Measure* measure, const int staffIdx, const int tick)
      {
      Key oldkey = score->staff(staffIdx)->key(tick);
      // TODO only if different custom key ?
      if (oldkey != key.key() || key.custom() || key.isAtonal()) {
            // new key differs from key in effect at this tick
            KeySig* keysig = new KeySig(score);
            keysig->setTrack((staffIdx) * VOICES);
            keysig->setKeySigEvent(key);
            keysig->setVisible(printObj);
            Segment* s = measure->getSegment(keysig, tick);
            s->add(keysig);
            //currKeySig->setKeySigEvent(key);
            }
      }

//---------------------------------------------------------
//   flushAlteredTone
//---------------------------------------------------------

/**
 If a valid key-step, -alter, -accidental combination has been read,
 convert it to a key symbol and add to the key.
 Clear key-step, -alter, -accidental.
 */

static void flushAlteredTone(KeySigEvent& kse, QString& step, QString& alt, QString& acc)
      {
      //qDebug("flushAlteredTone(step '%s' alt '%s' acc '%s')",
      //       qPrintable(step), qPrintable(alt), qPrintable(acc));

      if (step == "" && alt == "" && acc == "")
            return;  // nothing to do

      // step and alt are required, but also accept step and acc
      if (step != "" && (alt != "" || acc != "")) {
            addSymToSig(kse, step, alt, acc);
            }
      else {
            qDebug("flushAlteredTone invalid combination of step '%s' alt '%s' acc '%s')",
                   qPrintable(step), qPrintable(alt), qPrintable(acc)); // TODO
            }

      // clean up
      step = "";
      alt  = "";
      acc  = "";
      }

//---------------------------------------------------------
//   key
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/key node.
 */

// TODO: check currKeySig handling

void MusicXMLParserPass2::key(const QString& partId, Measure* measure, const int tick)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "key");

      QString strKeyno = _e.attributes().value("number").toString();
      int keyno = -1; // assume no number (see below)
      if (strKeyno != "") {
            keyno = strKeyno.toInt();
            if (keyno == 0) {
                  // conversion error (0), assume staff 1
                  _logger->logError(QString("invalid key number '%1'").arg(strKeyno), &_e);
                  keyno = 1;
                  }
            // convert to 0-based
            keyno--;
            }
      bool printObject = _e.attributes().value("print-object") != "no";

      // for custom keys, a single altered tone is described by
      // key-step (required),  key-alter (required) and key-accidental (optional)
      // none, one or more altered tone may be present
      // a simple state machine is required to detect them
      KeySigEvent key;
      QString keyStep;
      QString keyAlter;
      QString keyAccidental;

      while (_e.readNextStartElement()) {
            if (_e.name() == "fifths")
                  key.setKey(Key(_e.readElementText().toInt()));
            else if (_e.name() == "mode") {
                  QString m = _e.readElementText();
                  if (m == "none") {
                        key.setCustom(true);
                        key.setMode(KeyMode::NONE);
                        }
                  else if (m == "major") {
                        key.setMode(KeyMode::MAJOR);
                        }
                  else if (m == "minor") {
                        key.setMode(KeyMode::MINOR);
                        }
                  else {
                        _logger->logError(QString("Unsupported mode '%1'").arg(m), &_e);
                        }
                  }
            else if (_e.name() == "cancel")
                  skipLogCurrElem();  // TODO ??
            else if (_e.name() == "key-step") {
                  flushAlteredTone(key, keyStep, keyAlter, keyAccidental);
                  keyStep = _e.readElementText();
                  }
            else if (_e.name() == "key-alter")
                  keyAlter = _e.readElementText();
            else if (_e.name() == "key-accidental")
                  keyAccidental = _e.readElementText();
            else
                  skipLogCurrElem();
            }
      flushAlteredTone(key, keyStep, keyAlter, keyAccidental);

      int nstaves = _pass1.getPart(partId)->nstaves();
      int staffIdx = _pass1.trackForPart(partId) / VOICES;
      if (keyno == -1) {
            // apply key to all staves in the part
            for (int i = 0; i < nstaves; ++i) {
                  addKey(key, printObject, _score, measure, staffIdx + i, tick);
                  }
            }
      else if (keyno < nstaves)
            addKey(key, printObject, _score, measure, staffIdx + keyno, tick);
      }

//---------------------------------------------------------
//   clef
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/clef node.
 */

void MusicXMLParserPass2::clef(const QString& partId, Measure* measure, const int tick)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "clef");

      Part* part = _pass1.getPart(partId);
      Q_ASSERT(part);

      // TODO: check error handling for
      // - single staff
      // - multi-staff with same clef
      QString strClefno = _e.attributes().value("number").toString();
      int clefno = 1; // default
      if (strClefno != "")
            clefno = strClefno.toInt();
      if (clefno <= 0 || clefno > part->nstaves()) {
            // conversion error (0) or other issue, assume staff 1
            // Also for Cubase 6.5.5 which generates clef number="2" in a single staff part
            // Same fix is required in pass 1 and pass 2
            _logger->logError(QString("invalid clef number '%1'").arg(strClefno), &_e);
            clefno = 1;
            }
      // convert to 0-based
      clefno--;

      ClefType clef   = ClefType::G;
      StaffTypes st = StaffTypes::STANDARD;

      QString c;
      int i = 0;
      int line = -1;

      while (_e.readNextStartElement()) {
            if (_e.name() == "sign")
                  c = _e.readElementText();
            else if (_e.name() == "line")
                  line = _e.readElementText().toInt();
            else if (_e.name() == "clef-octave-change") {
                  i = _e.readElementText().toInt();
                  if (i && !(c == "F" || c == "G"))
                        qDebug("clef-octave-change only implemented for F and G key");  // TODO
                  }
            else
                  skipLogCurrElem();
            }

      //some software (Primus) don't include line and assume some default
      // it's permitted by MusicXML 2.0 XSD
      if (line == -1) {
            if (c == "G")
                  line = 2;
            else if (c == "F")
                  line = 4;
            else if (c == "C")
                  line = 3;
            }

      if (c == "G" && i == 0 && line == 2)
            clef = ClefType::G;
      else if (c == "G" && i == 1 && line == 2)
            clef = ClefType::G1;
      else if (c == "G" && i == 2 && line == 2)
            clef = ClefType::G2;
      else if (c == "G" && i == -1 && line == 2)
            clef = ClefType::G3;
      else if (c == "G" && i == 0 && line == 1)
            clef = ClefType::G4;
      else if (c == "F" && i == 0 && line == 3)
            clef = ClefType::F_B;
      else if (c == "F" && i == 0 && line == 4)
            clef = ClefType::F;
      else if (c == "F" && i == 1 && line == 4)
            clef = ClefType::F_8VA;
      else if (c == "F" && i == 2 && line == 4)
            clef = ClefType::F_15MA;
      else if (c == "F" && i == -1 && line == 4)
            clef = ClefType::F8;
      else if (c == "F" && i == -2 && line == 4)
            clef = ClefType::F15;
      else if (c == "F" && i == 0 && line == 5)
            clef = ClefType::F_C;
      else if (c == "C") {
            if (line == 5)
                  clef = ClefType::C5;
            else if (line == 4)
                  clef = ClefType::C4;
            else if (line == 3)
                  clef = ClefType::C3;
            else if (line == 2)
                  clef = ClefType::C2;
            else if (line == 1)
                  clef = ClefType::C1;
            }
      else if (c == "percussion") {
            clef = ClefType::PERC;
            st = StaffTypes::PERC_DEFAULT;
            }
      else if (c == "TAB") {
            clef = ClefType::TAB;
            st= StaffTypes::TAB_DEFAULT;
            }
      else
            qDebug("clef: unknown clef <sign=%s line=%d oct ch=%d>", qPrintable(c), line, i);  // TODO

      Clef* clefs = new Clef(_score);
      clefs->setClefType(clef);
      int track = _pass1.trackForPart(partId) + clefno * VOICES;
      clefs->setTrack(track);
      Segment* s = measure->getSegment(clefs, tick);
      s->add(clefs);

      // set the correct staff type
      // note that this overwrites the staff lines value set in pass 1
      // also note that clef handling should probably done in pass1
      int staffIdx = _score->staffIdx(part) + clefno;
      int lines = _score->staff(staffIdx)->lines();
      if (st == StaffTypes::TAB_DEFAULT || (_hasDrumset && st == StaffTypes::PERC_DEFAULT)) {
            _score->staff(staffIdx)->setStaffType(StaffType::preset(st));
            _score->staff(staffIdx)->setLines(lines); // preserve previously set staff lines
            _score->staff(staffIdx)->setBarLineTo((lines - 1) * 2);
            }
      }

//---------------------------------------------------------
//   determineTimeSig
//---------------------------------------------------------

/**
 Determine the time signature based on \a beats, \a beatType and \a timeSymbol.
 Sets return parameters \a st, \a bts, \a btp.
 Return true if OK, false on error.
 */

// TODO: share between pass 1 and pass 2

static bool determineTimeSig(const QString beats, const QString beatType, const QString timeSymbol,
                             TimeSigType& st, int& bts, int& btp)
      {
      // initialize
      st  = TimeSigType::NORMAL;
      bts = 0;       // the beats (max 4 separated by "+") as integer
      btp = 0;       // beat-type as integer
      // determine if timesig is valid
      if (beats == "2" && beatType == "2" && timeSymbol == "cut") {
            st = TimeSigType::ALLA_BREVE;
            bts = 2;
            btp = 2;
            return true;
            }
      else if (beats == "4" && beatType == "4" && timeSymbol == "common") {
            st = TimeSigType::FOUR_FOUR;
            bts = 4;
            btp = 4;
            return true;
            }
      else {
            if (!timeSymbol.isEmpty() && timeSymbol != "normal") {
                  qDebug("determineTimeSig: time symbol <%s> not recognized with beats=%s and beat-type=%s",
                         qPrintable(timeSymbol), qPrintable(beats), qPrintable(beatType)); // TODO
                  return false;
                  }

            btp = beatType.toInt();
            QStringList list = beats.split("+");
            for (int i = 0; i < list.size(); i++)
                  bts += list.at(i).toInt();
            }

      // determine if bts and btp are valid
      if (bts <= 0 || btp <=0) {
            qDebug("determineTimeSig: beats=%s and/or beat-type=%s not recognized",
                   qPrintable(beats), qPrintable(beatType));         // TODO
            return false;
            }

      return true;
      }

//---------------------------------------------------------
//   time
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/time node.
 */

void MusicXMLParserPass2::time(const QString& partId, Measure* measure, const int tick)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "time");

      QString beats;
      QString beatType;
      QString timeSymbol = _e.attributes().value("symbol").toString();
      bool printObject = _e.attributes().value("print-object") != "no";

      while (_e.readNextStartElement()) {
            if (_e.name() == "beats")
                  beats = _e.readElementText();
            else if (_e.name() == "beat-type")
                  beatType = _e.readElementText();
            else
                  skipLogCurrElem();
            }

      if (beats != "" && beatType != "") {
            // determine if timesig is valid
            TimeSigType st  = TimeSigType::NORMAL;
            int bts = 0; // total beats as integer (beats may contain multiple numbers, separated by "+")
            int btp = 0; // beat-type as integer
            if (determineTimeSig(beats, beatType, timeSymbol, st, bts, btp)) {
                  _timeSigDura = Fraction(bts, btp);
                  Fraction fractionTSig = Fraction(bts, btp);
                  for (int i = 0; i < _pass1.getPart(partId)->nstaves(); ++i) {
                        TimeSig* timesig = new TimeSig(_score);
                        timesig->setVisible(printObject);
                        int track = _pass1.trackForPart(partId) + i * VOICES;
                        timesig->setTrack(track);
                        timesig->setSig(fractionTSig, st);
                        // handle simple compound time signature
                        if (beats.contains(QChar('+'))) {
                              timesig->setNumeratorString(beats);
                              timesig->setDenominatorString(beatType);
                              }
                        Segment* s = measure->getSegment(timesig, tick);
                        s->add(timesig);
                        }
                  }
            }
      }

//---------------------------------------------------------
//   transpose
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/transpose node.
 */

void MusicXMLParserPass2::transpose(const QString& partId)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "transpose");

      Interval interval;
      bool diatonic = false;
      bool chromatic = false;
      while (_e.readNextStartElement()) {
            int i = _e.readElementText().toInt();
            if (_e.name() == "diatonic") {
                  interval.diatonic = i;
                  diatonic = true;
                  }
            else if (_e.name() == "chromatic") {
                  interval.chromatic = i;
                  chromatic = true;
                  }
            else if (_e.name() == "octave-change") {
                  interval.diatonic += i * 7;
                  interval.chromatic += i * 12;
                  }
            else
                  skipLogCurrElem();
            }

      if (chromatic && !diatonic)
            interval.diatonic += chromatic2diatonic(interval.chromatic);

      _pass1.getPart(partId)->instrument()->setTranspose(interval);
      }

//---------------------------------------------------------
//   divisions
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/attributes/divisions node.
 */

void MusicXMLParserPass2::divisions()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "divisions");

      _divs = _e.readElementText().toInt();
      if (!(_divs > 0))
            _logger->logError("illegal divisions", &_e);
      }

//---------------------------------------------------------
//   isWholeMeasureRest
//---------------------------------------------------------

/**
 * Determine whole measure rest.
 */

// By convention, whole measure rests do not have a "type" element
// As of MusicXML 3.0, this can be indicated by an attribute "measure",
// but for backwards compatibility the "old" convention still has to be supported.
// Also verify the rest fits exactly in the measure, as some programs
// (e.g. Cakewalk SONAR X2 Studio [Version: 19.0.0.306]) leave out
// the type for all rests.
// Sibelius calls all whole-measure rests "whole", even if the duration != 4/4

static bool isWholeMeasureRest(const bool rest, const QString& type, const Fraction dura, const Fraction mDura)
      {
      if (!rest)
            return false;

      if (!dura.isValid())
            return false;

      if (!mDura.isValid())
            return false;

      return ((type == "" && dura == mDura)
              || (type == "whole" && dura == mDura && dura != Fraction(1, 1)));
      }

//---------------------------------------------------------
//   determineDuration
//---------------------------------------------------------

/**
 * Determine duration for a note or rest.
 * This includes whole measure rest detection.
 */

static TDuration determineDuration(const bool rest, const QString& type, const int dots, const Fraction dura, const Fraction mDura)
      {
      //qDebug("determineDuration rest %d type '%s' dots %d dura %s mDura %s",
      //       rest, qPrintable(type), dots, qPrintable(dura.print()), qPrintable(mDura.print()));

      TDuration res;
      if (rest) {
            if (isWholeMeasureRest(rest, type, dura, mDura))
                  res.setType(TDuration::DurationType::V_MEASURE);
            else if (type == "") {
                  // If no type, set duration type based on duration.
                  // Note that sometimes unusual duration (e.g. 261/256) are found.
                  res.setVal(dura.ticks());
                  }
            else {
                  res.setType(type);
                  res.setDots(dots);
                  }
            }
      else {
            res.setType(type);
            res.setDots(dots);
            if (res.type() == TDuration::DurationType::V_INVALID)
                  res.setType(TDuration::DurationType::V_QUARTER);  // default, TODO: use dura ?
            }

      //qDebug("-> dur %hhd (%s) dots %d ticks %s",
      //       res.type(), qPrintable(res.name()), res.dots(), qPrintable(dura.print()));

      return res;
      }

//---------------------------------------------------------
//   setChordRestDuration
//---------------------------------------------------------

/**
 * Set \a cr duration
 */

static void setChordRestDuration(ChordRest* cr, TDuration duration, const Fraction dura)
      {
      if (duration.type() == TDuration::DurationType::V_MEASURE) {
            cr->setDurationType(duration);
            cr->setDuration(dura);
            }
      else {
            cr->setDurationType(duration);
            cr->setDuration(cr->durationType().fraction());
            }
      }

//---------------------------------------------------------
//   addRest
//---------------------------------------------------------

/**
 * Add a rest to the score
 * TODO: beam handling
 * TODO: display step handling
 * TODO: visible handling
 * TODO: whole measure rest handling
 */

static Rest* addRest(Score* score, Measure* m,
                     const int tick, const int track, const int move,
                     const TDuration duration, const Fraction dura)
      {
      Segment* s = m->getSegment(Segment::Type::ChordRest, tick);
      // Sibelius might export two rests at the same place, ignore the 2nd one
      // <?DoletSibelius Two NoteRests in same voice at same position may be an error?>
      if (s->element(track)) {
            qDebug("cannot add rest at tick %d track %d: element already present", tick, track);       // TODO
            return 0;
            }

      Rest* cr = new Rest(score);
      setChordRestDuration(cr, duration, dura);
      cr->setTrack(track);
      cr->setStaffMove(move);
      s->add(cr);
      return cr;
      }

//---------------------------------------------------------
//   findOrCreateChord
//---------------------------------------------------------

/**
 * Find (or create if not found) the chord at \a tick and \a track.
 * Note: staff move is a note property in MusicXML, but chord property in MuseScore
 * This is simply ignored here, effectively using the last chords value.
 */

static Chord* findOrCreateChord(Score* score, Measure* m,
                                const int tick, const int track, const int move,
                                const TDuration duration, const Fraction dura,
                                Beam::Mode bm)
      {
      //qDebug("findOrCreateChord tick %d track %d dur ticks %d ticks %s bm %hhd",
      //       tick, track, duration.ticks(), qPrintable(dura.print()), bm);
      Chord* c = m->findChord(tick, track);
      if (c == 0) {
            c = new Chord(score);
            // better not to force beam end, as the beam palette does not support it
            if (bm == Beam::Mode::END)
                  c->setBeamMode(Beam::Mode::AUTO);
            else
                  c->setBeamMode(bm);
            c->setTrack(track);

            setChordRestDuration(c, duration, dura);
            Segment* s = m->getSegment(c, tick);
            s->add(c);
            }
      c->setStaffMove(move);
      return c;
      }

//---------------------------------------------------------
//   graceNoteType
//---------------------------------------------------------

/**
 * convert duration and slash to grace note type
 */

NoteType graceNoteType(const TDuration duration, const bool slash)
      {
      NoteType nt = NoteType::APPOGGIATURA;
      if (slash)
            nt = NoteType::ACCIACCATURA;
      if (duration.type() == TDuration::DurationType::V_QUARTER) {
            nt = NoteType::GRACE4;
            }
      else if (duration.type() == TDuration::DurationType::V_16TH) {
            nt = NoteType::GRACE16;
            }
      else if (duration.type() == TDuration::DurationType::V_32ND) {
            nt = NoteType::GRACE32;
            }
      return nt;
      }

//---------------------------------------------------------
//   createGraceChord
//---------------------------------------------------------

/**
 * Create a grace chord.
 */

static Chord* createGraceChord(Score* score, const int track,
                               const TDuration duration, const bool slash)
      {
      Chord* c = new Chord(score);
      c->setNoteType(graceNoteType(duration, slash));
      c->setTrack(track);
      // note grace notes have no durations, use default fraction 0/1
      setChordRestDuration(c, duration, Fraction());
      return c;
      }

//---------------------------------------------------------
//   elementMustBePostponed
//---------------------------------------------------------

/**
 Check if handling the current element must be postponed
 until after allocating the note.
 */

static bool elementMustBePostponed(const QXmlStreamReader& e)
      {
      return e.name() == "notations"
             || e.name() == "lyric"
             || e.name() == "play";
      }

//---------------------------------------------------------
//   handleDisplayStep
//---------------------------------------------------------

/**
 * convert display-step and display-octave to staff line
 */

static void handleDisplayStep(ChordRest* cr, int step, int octave, int tick, qreal spatium)
      {
      if (0 <= step && step <= 6 && 0 <= octave && octave <= 9) {
            //qDebug("rest step=%d oct=%d", step, octave);
            ClefType clef = cr->staff()->clef(tick);
            int po = ClefInfo::pitchOffset(clef);
            //qDebug(" clef=%hhd po=%d step=%d", clef, po, step);
            int dp = 7 * (octave + 2) + step;
            //qDebug(" dp=%d po-dp=%d", dp, po-dp);
            cr->setUserYoffset((po - dp + 3) * spatium / 2);
            }
      }

//---------------------------------------------------------
//   setNoteHead
//---------------------------------------------------------

/**
 Set the notehead parameters.
 */

static void setNoteHead(Note* note, const QColor noteheadColor, const bool noteheadParentheses, const QString& noteheadFilled)
      {
      const auto score = note->score();

      if (noteheadColor != QColor::Invalid)
            note->setColor(noteheadColor);
      if (noteheadParentheses) {
            auto s = new Symbol(score);
            s->setSym(SymId::noteheadParenthesisLeft);
            s->setParent(note);
            score->addElement(s);
            s = new Symbol(score);
            s->setSym(SymId::noteheadParenthesisRight);
            s->setParent(note);
            score->addElement(s);
            }

      if (noteheadFilled == "no")
            note->setHeadType(NoteHead::Type::HEAD_HALF);
      else if (noteheadFilled == "yes")
            note->setHeadType(NoteHead::Type::HEAD_QUARTER);
      }

//---------------------------------------------------------
//   addFiguredBassElemens
//---------------------------------------------------------

/**
 Add the figured bass elements.
 */

static void addFiguredBassElemens(FiguredBassList& fbl, const Fraction noteStartTime, const int msTrack,
                                  const Fraction dura, Measure* measure)
      {
      if (!fbl.isEmpty()) {
            auto sTick = noteStartTime.ticks();                    // starting tick
            foreach (FiguredBass* fb, fbl) {
                  fb->setTrack(msTrack);
                  // No duration tag defaults ticks() to 0; set to note value
                  if (fb->ticks() == 0)
                        fb->setTicks(dura.ticks());
                  // TODO: set correct onNote value
                  Segment* s = measure->getSegment(Segment::Type::ChordRest, sTick);
                  s->add(fb);
                  sTick += fb->ticks();
                  }
            fbl.clear();
            }
      }

//---------------------------------------------------------
//   note
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note node.
 */

Note* MusicXMLParserPass2::note(const QString& partId,
                                Measure* measure,
                                const Fraction sTime,
                                const Fraction prevSTime,
                                Fraction& dura,
                                QString& currentVoice,
                                GraceChordList& gcl,
                                int& gac,
                                Beam*& currBeam,
                                FiguredBassList& fbl,
                                int& alt
                                )
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "note");

      if (_e.attributes().value("print-spacing") == "no") {
            notePrintSpacingNo(dura);
            return 0;
            }

      bool chord = false;
      bool cue = false;
      bool small = false;
      bool grace = false;
      bool rest = false;
      int staff = 1;
      QString type;
      QString voice;
      MScore::Direction stemDir = MScore::Direction::AUTO;
      bool noStem = false;
      NoteHead::Group headGroup = NoteHead::Group::HEAD_NORMAL;
      QColor noteColor = QColor::Invalid;
      noteColor.setNamedColor(_e.attributes().value("color").toString());
      QColor noteheadColor = QColor::Invalid;
      bool noteheadParentheses = false;
      QString noteheadFilled;
      int velocity = round(_e.attributes().value("dynamics").toDouble() * 0.9);
      bool graceSlash = false;
      bool printObject = _e.attributes().value("print-object") != "no";
      Beam::Mode bm  = Beam::Mode::AUTO;
      QString instrumentId;

      mxmlNoteDuration mnd(_divs, _logger);
      mxmlNotePitch mnp(_logger);

      while (_e.readNextStartElement() && !elementMustBePostponed(_e)) {
            if (mnp.readProperties(_e, _score)) {
                  // element handled
                  }
            else if (mnd.readProperties(_e)) {
                  // element handled
                  }
            else if (_e.name() == "beam")
                  beam(bm);
            else if (_e.name() == "chord") {
                  chord = true;
                  _e.readNext();
                  }
            else if (_e.name() == "cue") {
                  cue = true;
                  _e.readNext();
                  }
            else if (_e.name() == "grace") {
                  grace = true;
                  graceSlash = _e.attributes().value("slash") == "yes";
                  _e.readNext();
                  }
            else if (_e.name() == "instrument") {
                  instrumentId = _e.attributes().value("id").toString();
                  _e.readNext();
                  }
            else if (_e.name() == "notehead") {
                  noteheadColor.setNamedColor(_e.attributes().value("color").toString());
                  noteheadParentheses = _e.attributes().value("parentheses") == "yes";
                  noteheadFilled = _e.attributes().value("filled").toString();
                  headGroup = convertNotehead(_e.readElementText());
                  }
            else if (_e.name() == "rest") {
                  rest = true;
                  mnp.displayStepOctave(_e);
                  }
            else if (_e.name() == "staff") {
                  auto ok = false;
                  auto strStaff = _e.readElementText();
                  staff = strStaff.toInt(&ok);
                  if (!ok) {
                        // error already reported in pass 1
                        staff = 1;
                        }
                  }
            else if (_e.name() == "stem")
                  stem(stemDir, noStem);
            else if (_e.name() == "type") {
                  small = _e.attributes().value("size") == "cue";
                  type = _e.readElementText();
                  }
            else if (_e.name() == "voice")
                  voice = _e.readElementText();
            else
                  skipLogCurrElem();
            }

      // convert staff to zero-based (in case of error, staff will be -1)
      staff--;

      // Bug fix for Sibelius 7.1.3 which does not write <voice> for notes with <chord>
      if (!chord)
            // remember voice
            currentVoice = voice;
      else if (voice == "")
            // use voice from last note w/o <chord>
            voice = currentVoice;

      // Assume voice 1 if voice is empty (legal in a single voice part)
      if (voice == "")
            voice = "1";

      // check for timing error(s) and set dura
      // keep in this order as checkTiming() might change dura
      auto errorStr = mnd.checkTiming(type, rest, grace);
      dura = mnd.dura();
      if (errorStr != "")
            _logger->logError(errorStr, &_e);

      // At this point all checks have been done, the note should be added
      // note: in case of error exit from here, the postponed <note> children
      // must still be skipped

      int msMove = 0;
      int msTrack = 0;
      int msVoice = 0;

      if (!_pass1.determineStaffMoveVoice(partId, staff, voice, msMove, msTrack, msVoice)) {
            _logger->logDebugInfo(QString("could not map staff %1 voice '%2'").arg(staff + 1).arg(voice), &_e);
            // begin experimental fix for postponed <note> children
            // TODO test /repair
#if 0
            while (_e.tokenType() == QXmlStreamReader::StartElement) {

                  //qDebug("in second loop element '%s'", qPrintable(_e.name().toString()));
                  skipLogCurrElem();

                  // skip to either start of next <note> child or end of <note>
                  // currently at end of last <note> child handled
                  //qDebug("::note before skip tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));
                  do
                        _e.readNext();
                  while (!(_e.tokenType() == QXmlStreamReader::StartElement)
                         && !(_e.tokenType() == QXmlStreamReader::EndElement && _e.name() == "note"));
                  //qDebug("::note after skip tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));


                  }
#endif
            // end experimental fix for testVoiceMapper*
            return 0;
            }
      else {
            }

      TDuration duration = determineDuration(rest, type, mnd.dots(), dura, Fraction::fromTicks(measure->ticks()));

      ChordRest* cr = 0;
      Note* note = 0;

      // start time for note:
      // - sTime for non-chord / first chord note
      // - prevTime for others
      const Fraction noteStartTime = chord ? prevSTime : sTime;

      if (rest) {
            int track = msTrack + msVoice;
            cr = addRest(_score, measure, noteStartTime.ticks(), track, msMove,
                         duration, dura);
            if (cr) {
                  if (currBeam) {
                        if (currBeam->track() == track) {
                              cr->setBeamMode(Beam::Mode::MID);
                              currBeam->add(cr);
                              }
                        else
                              removeBeam(currBeam);
                        }
                  else
                        cr->setBeamMode(Beam::Mode::NONE);
                  cr->setSmall(small);
                  if (noteColor != QColor::Invalid)
                        cr->setColor(noteColor);
                  cr->setVisible(printObject);
                  handleDisplayStep(cr, mnp.displayStep(), mnp.displayOctave(), noteStartTime.ticks(), _score->spatium());
                  }
            }
      else {
            Chord* c;
            if (!grace) {
                  // regular note
                  // if there is already a chord just add to it
                  // else create a new one
                  // this basically ignores <chord/> errors
                  c = findOrCreateChord(_score, measure,
                                        noteStartTime.ticks(),
                                        msTrack + msVoice, msMove,
                                        duration, dura, bm);
                  // handle beam
                  if (!chord)
                        handleBeamAndStemDir(c, bm, stemDir, currBeam);

                  // append any grace chord after chord to the previous chord
                  Chord* prevChord = measure->findChord(prevSTime.ticks(), msTrack + msVoice);
                  if (prevChord && prevChord != c)
                        addGraceChordsAfter(prevChord, gcl, gac);

                  // append any grace chord
                  addGraceChordsBefore(c, gcl);
                  }
            else {
                  // grace note
                  // TODO: check if explicit stem direction should also be set for grace notes
                  // (the DOM parser does that, but seems to have no effect on the autotester)
                  if (!chord || gcl.isEmpty()) {
                        c = createGraceChord(_score, msTrack + msVoice, duration, graceSlash);
                        // TODO FIX
                        // the setStaffMove() below results in identical behaviour as 2.0:
                        // grace note will be at the wrong staff with the wrong pitch,
                        // seems to use the line value calculated for the right staff
                        // leaving it places the note at the wrong staff with the right pitch
                        // this affects only grace notes where staff move differs from
                        // the main note, e.g. DebuMandSample.xml first grace in part 2
                        // c->setStaffMove(msMove);
                        // END TODO
                        gcl.append(c);
                        }
                  else
                        c = gcl.last();

                  }
            note = new Note(_score);
            note->setSmall(small);
            note->setHeadGroup(headGroup);
            if (noteColor != QColor::Invalid)
                  note->setColor(noteColor);
            setNoteHead(note, noteheadColor, noteheadParentheses, noteheadFilled);
            note->setVisible(printObject); // TODO also set the stem to invisible

            if (velocity > 0) {
                  note->setVeloType(Note::ValueType::USER_VAL);
                  note->setVeloOffset(velocity);
                  }

            const MusicXMLDrumset& mxmlDrumset = _pass1.getDrumset(partId);
            if (mnp.unpitched()) {
                  //&& drumsets.contains(partId)
                  if (_hasDrumset
                      && mxmlDrumset.contains(instrumentId)) {
                        // step and oct are display-step and ...-oct
                        // get pitch from instrument definition in drumset instead
                        int pitch = mxmlDrumset[instrumentId].pitch;
                        note->setPitch(limit(pitch, 0, 127));
                        // TODO - does this need to be key-aware?
                        note->setTpc(pitch2tpc(pitch, Key::C, Prefer::NEAREST)); // TODO: necessary ?
                        }
                  else {
                        //qDebug("disp step %d oct %d", displayStep, displayOctave);
                        xmlSetPitch(note, mnp.displayStep(), 0, mnp.displayOctave(), 0, _pass1.getPart(partId)->instrument());
                        }
                  }
            else {
                  int ottavaStaff = (msTrack - _pass1.trackForPart(partId)) / VOICES;
                  int octaveShift = _pass1.octaveShift(partId, ottavaStaff, noteStartTime);
                  xmlSetPitch(note, mnp.step(), mnp.alter(), mnp.octave(), octaveShift, _pass1.getPart(partId)->instrument());
                  }

            // set drumset information
            // note that in MuseScore, the drumset contains defaults for notehead,
            // line and stem direction, while a MusicXML file contains actuals.
            // the MusicXML values for each note are simply copied to the defaults

            if (mnp.unpitched()) {
                  // determine staff line based on display-step / -octave and clef type
                  ClefType clef = c->staff()->clef(noteStartTime.ticks());
                  int po = ClefInfo::pitchOffset(clef);
                  int pitch = MusicXMLStepAltOct2Pitch(mnp.displayStep(), 0, mnp.displayOctave());
                  int line = po - absStep(pitch);

                  // correct for number of staff lines
                  // see ExportMusicXml::unpitch2xml for explanation
                  // TODO handle other # staff lines ?
                  int staffLines = c->staff()->lines();
                  if (staffLines == 1) line -= 8;
                  if (staffLines == 3) line -= 2;

                  // the drum palette cannot handle stem direction AUTO,
                  // overrule if necessary
                  if (stemDir == MScore::Direction::AUTO) {
                        if (line > 4)
                              stemDir = MScore::Direction::DOWN;
                        else
                              stemDir = MScore::Direction::UP;
                        }

                  /*
                  if (drumsets.contains(partId)
                       && mxmlDrumset.contains(instrId)) {
                        mxmlDrumset[instrId].notehead = headGroup;
                        mxmlDrumset[instrId].line = line;
                        mxmlDrumset[instrId].stemDirection = sd;
                  }
                   */
                  // this should be done in pass 1, would make _pass1 const here
                  _pass1.setDrumsetDefault(partId, instrumentId, headGroup, line, stemDir);
                  }

            // accidental handling
            //qDebug("note acc %p type %hhd acctype %hhd",
            //       acc, acc ? acc->accidentalType() : static_cast<Ms::AccidentalType>(0), accType);
            Accidental* acc = mnp.acc();
            if (!acc && mnp.accType() != AccidentalType::NONE) {
                  acc = new Accidental(_score);
                  acc->setAccidentalType(mnp.accType());
                  }

            if (acc) {
                  note->add(acc);
                  // save alter value for user accidental
                  if (acc->accidentalType() != AccidentalType::NONE)
                        alt = mnp.alter();
                  }

            c->add(note);
            //c->setStemDirection(stemDir); // already done in handleBeamAndStemDir()
            c->setNoStem(noStem);
            cr = c;
            }

      // cr can be 0 here (if a rest cannot be added)
      // TODO: complete and cleanup handling this case
      if (cr) {
            cr->setVisible(printObject);
            if (cue) cr->setSmall(cue);  // only once per chord
            }

      // handle the postponed children of <note>
      // if one of these was found, the first while loop was terminated
      // at a StartElement instead of the usual EndElement

      QMap<int, Lyrics*> numberedLyrics; // lyrics with valid number
      QSet<Lyrics*> extendedLyrics;      // lyrics with the extend flag set
      MusicXmlTupletDesc tupletDesc;
      bool lastGraceAFter = false;       // set by notations() if end of grace after sequence found

      while (_e.tokenType() == QXmlStreamReader::StartElement) {

            //qDebug("in second loop element '%s'", qPrintable(_e.name().toString()));
            if (_e.name() == "lyric") {
                  // lyrics on grace notes not (yet) supported by MuseScore
                  if (!grace)
                        lyric(partId, numberedLyrics, extendedLyrics);  // TODO: move track handling to addlyric
                  else {
                        _logger->logDebugInfo("ignoring lyrics on grace notes", &_e);
                        skipLogCurrElem();
                        }
                  }
            else if (_e.name() == "notations")
                  notations(note, cr, noteStartTime.ticks(), tupletDesc, lastGraceAFter);
            else
                  skipLogCurrElem();

            // skip to either start of next <note> child or end of <note>
            // currently at end of last <note> child handled
            //qDebug("::note before skip tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));
            do
                  _e.readNext();
            while (!(_e.tokenType() == QXmlStreamReader::StartElement)
                   && !(_e.tokenType() == QXmlStreamReader::EndElement && _e.name() == "note"));
            //qDebug("::note after skip tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));

            }

      //qDebug("::note after second loop tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));

      // handle grace after state: remember current grace list size
      if (grace && lastGraceAFter)
            gac = gcl.size();

      if (cr) {
            if (!chord && !grace) {
                  // do tuplet if valid time-modification is not 1/1 and is not 1/2 (tremolo)
                  auto timeMod = mnd.timeMod();
                  if (timeMod.isValid() && timeMod != Fraction(1, 1) && timeMod != Fraction(1, 2)) {
                        // find part-relative track
                        Part* part = _pass1.getPart(partId);
                        Q_ASSERT(part);
                        int scoreRelStaff = _score->staffIdx(part); // zero-based number of parts first staff in the score
                        int partRelTrack = msTrack + msVoice - scoreRelStaff * VOICES;
                        addTupletToChord(cr, _tuplets[partRelTrack], _tuplImpls[partRelTrack], timeMod, tupletDesc, mnd.normalType());
                        }
                  }
            }

      // add lyrics found by lyric
      if (cr) {
            // add lyrics and stop corresponding extends
            addLyrics(_logger, &_e, cr, numberedLyrics, extendedLyrics, _extendedLyrics);
            if (rest) {
                  // stop all extends
                  _extendedLyrics.setExtend(-1, cr->track(), cr->tick());
                  }
            }

      // add figured bass element
      addFiguredBassElemens(fbl, noteStartTime, msTrack, dura, measure);

      // don't count chord or grace note duration
      // note that this does not check the MusicXML requirement that notes in a chord
      // cannot have a duration longer than the first note in the chord
      if (chord || grace)
            dura.set(0, 1);

      if (!(_e.isEndElement() && _e.name() == "note"))
            qDebug("name %s line %lld", qPrintable(_e.name().toString()), _e.lineNumber());
      Q_ASSERT(_e.isEndElement() && _e.name() == "note");

      return note;
      }

//---------------------------------------------------------
//   notePrintSpacingNo
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note node for a note with print-spacing="no".
 These are handled like a forward: only moving the time forward.
 */

void MusicXMLParserPass2::notePrintSpacingNo(Fraction& dura)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "note");
      //_logger->logDebugTrace("MusicXMLParserPass1::notePrintSpacingNo", &_e);

      bool chord = false;
      bool grace = false;

      while (_e.readNextStartElement()) {
            if (_e.name() == "chord") {
                  chord = true;
                  _e.readNext();
                  }
            else if (_e.name() == "duration")
                  duration(dura);
            else if (_e.name() == "grace") {
                  grace = true;
                  _e.readNext();
                  }
            else
                  _e.skipCurrentElement();        // skip but don't log
            }

      // don't count chord or grace note duration
      // note that this does not check the MusicXML requirement that notes in a chord
      // cannot have a duration longer than the first note in the chord
      if (chord || grace)
            dura.set(0, 1);

      Q_ASSERT(_e.isEndElement() && _e.name() == "note");
      }

//---------------------------------------------------------
//   calcTicks
//---------------------------------------------------------

static Fraction calcTicks(const QString& text, int divs)
      {
      Fraction dura(0, 0);        // invalid unless set correctly

      int intDura = text.toInt();
      if (divs > 0)
            dura.set(intDura, 4 * divs);
      else
            qDebug("illegal or uninitialized divisions (%d)", divs);       // TODO

      return dura;
      }

//---------------------------------------------------------
//   duration
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/duration node.
 */

void MusicXMLParserPass2::duration(Fraction& dura)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "duration");

      dura.set(0, 0);        // invalid unless set correctly
      int intDura = _e.readElementText().toInt();
      if (intDura > 0) {
            if (_divs > 0) {
                  dura.set(intDura, 4 * _divs);
                  dura.reduce(); // prevent overflow in later Fraction operations
                  }
            else
                  _logger->logError(QString("illegal or uninitialized divisions (%1)").arg(_divs), &_e);
            }
      else
            _logger->logError(QString("illegal duration %1").arg(dura.print()), &_e);
      //qDebug("duration %s valid %d", qPrintable(dura.print()), dura.isValid());
      }

//---------------------------------------------------------
//   figure
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/harmony/figured-bass/figure node.
 Return the result as a FiguredBassItem.
 */

FiguredBassItem* MusicXMLParserPass2::figure(const int idx, const bool paren)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "figure");

      FiguredBassItem* fgi = new FiguredBassItem(_score, idx);

      // read the figure
      while (_e.readNextStartElement()) {
            if (_e.name() == "extend") {
                  QStringRef type = _e.attributes().value("type");
                  if (type == "start")
                        fgi->setContLine(FiguredBassItem::ContLine::EXTENDED);
                  else if (type == "continue")
                        fgi->setContLine(FiguredBassItem::ContLine::EXTENDED);
                  else if (type == "stop")
                        fgi->setContLine(FiguredBassItem::ContLine::SIMPLE);
                  _e.skipCurrentElement();
                  }
            else if (_e.name() == "figure-number") {
                  QString val = _e.readElementText();
                  int iVal = val.toInt();
                  // MusicXML spec states figure-number is a number
                  // MuseScore can only handle single digit
                  if (1 <= iVal && iVal <= 9)
                        fgi->setDigit(iVal);
                  else
                        _logger->logError(QString("incorrect figure-number '%1'").arg(val), &_e);
                  }
            else if (_e.name() == "prefix")
                  fgi->setPrefix(fgi->MusicXML2Modifier(_e.readElementText()));
            else if (_e.name() == "suffix")
                  fgi->setSuffix(fgi->MusicXML2Modifier(_e.readElementText()));
            else
                  skipLogCurrElem();
            }

      // set parentheses
      if (paren) {
            // parenthesis open
            if (fgi->prefix() != FiguredBassItem::Modifier::NONE)
                  fgi->setParenth1(FiguredBassItem::Parenthesis::ROUNDOPEN);        // before prefix
            else if (fgi->digit() != FBIDigitNone)
                  fgi->setParenth2(FiguredBassItem::Parenthesis::ROUNDOPEN);        // before digit
            else if (fgi->suffix() != FiguredBassItem::Modifier::NONE)
                  fgi->setParenth3(FiguredBassItem::Parenthesis::ROUNDOPEN);        // before suffix
            // parenthesis close
            if (fgi->suffix() != FiguredBassItem::Modifier::NONE)
                  fgi->setParenth4(FiguredBassItem::Parenthesis::ROUNDCLOSED);        // after suffix
            else if (fgi->digit() != FBIDigitNone)
                  fgi->setParenth3(FiguredBassItem::Parenthesis::ROUNDCLOSED);        // after digit
            else if (fgi->prefix() != FiguredBassItem::Modifier::NONE)
                  fgi->setParenth2(FiguredBassItem::Parenthesis::ROUNDCLOSED);        // after prefix
            }

      return fgi;
      }

//---------------------------------------------------------
//   figuredBass
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/harmony/figured-bass node.
 TODO check description:
 // Set the FiguredBass state based on the MusicXML <figured-bass> node de.
 // Note that onNote and ticks must be set by the MusicXML importer,
 // as the required context is not present in the items DOM tree.
 // Exception: if a <duration> element is present, tick can be set.
 Return the result as a FiguredBass if valid, non-empty figure(s) are found.
 Return 0 in case of error.
 */

FiguredBass* MusicXMLParserPass2::figuredBass()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "figured-bass");

      FiguredBass* fb = new FiguredBass(_score);

      bool parentheses = _e.attributes().value("parentheses") == "yes";
      QString normalizedText;
      int idx = 0;
      while (_e.readNextStartElement()) {
            if (_e.name() == "duration") {
                  Fraction dura;
                  duration(dura);
                  if (dura.isValid() && dura > Fraction(0, 1))
                        fb->setTicks(dura.ticks());
                  }
            else if (_e.name() == "figure") {
                  FiguredBassItem* pItem = figure(idx++, parentheses);
                  pItem->setTrack(0 /* TODO fb->track() */);
                  pItem->setParent(fb);
                  fb->appendItem(pItem);
                  // add item normalized text
                  if (!normalizedText.isEmpty())
                        normalizedText.append('\n');
                  normalizedText.append(pItem->normalizedText());
                  }
            else {
                  skipLogCurrElem();
                  delete fb;
                  return 0;
                  }
            }

      fb->setXmlText(normalizedText);                        // this is the text to show while editing

      if (normalizedText.isEmpty()) {
            delete fb;
            return 0;
            }

      return fb;
      }

//---------------------------------------------------------
//   frame
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/harmony/frame node.
 Return the result as a FretDiagram.
 */

FretDiagram* MusicXMLParserPass2::frame()
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "frame");

      FretDiagram* fd = new FretDiagram(_score);

      while (_e.readNextStartElement()) {
            if (_e.name() == "frame-frets") {
                  int val = _e.readElementText().toInt();
                  if (val > 0)
                        fd->setFrets(val);
                  else
                        _logger->logError(QString("FretDiagram::readMusicXML: illegal frame-fret %1").arg(val), &_e);
                  }
            else if (_e.name() == "frame-note") {
                  int fret   = -1;
                  int string = -1;
                  while (_e.readNextStartElement()) {
                        if (_e.name() == "fret")
                              fret = _e.readElementText().toInt();
                        else if (_e.name() == "string")
                              string = _e.readElementText().toInt();
                        else
                              skipLogCurrElem();
                        }
                  _logger->logDebugInfo(QString("FretDiagram::readMusicXML string %1 fret %2").arg(string).arg(fret), &_e);
                  if (string > 0) {
                        if (fret == 0)
                              fd->setMarker(fd->strings() - string, 79 /* ??? */);
                        else if (fret > 0)
                              fd->setDot(fd->strings() - string, fret);
                        }
                  }
            else if (_e.name() == "frame-strings") {
                  int val = _e.readElementText().toInt();
                  if (val > 0) {
                        fd->setStrings(val);
                        for (int i = 0; i < val; ++i)
                              fd->setMarker(i, 88 /* ??? */);
                        }
                  else
                        _logger->logError(QString("FretDiagram::readMusicXML: illegal frame-strings %1").arg(val), &_e);
                  }
            else
                  skipLogCurrElem();
            }

      return fd;
      }

//---------------------------------------------------------
//   harmony
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/harmony node.
 */

void MusicXMLParserPass2::harmony(const QString& partId, Measure* measure, const Fraction sTime)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "harmony");

      int track = _pass1.trackForPart(partId);

      // placement:
      // in order to work correctly, this should probably be adjusted to account for spatium
      // but in any case, we don't support import relative-x/y for other elements
      // no reason to do so for chord symbols
      double rx = 0.0;        // 0.1 * e.attribute("relative-x", "0").toDouble();
      double ry = 0.0;        // -0.1 * e.attribute("relative-y", "0").toDouble();

      double styleYOff = _score->textStyle(TextStyleType::HARMONY).offset().y();
      OffsetType offsetType = _score->textStyle(TextStyleType::HARMONY).offsetType();
      if (offsetType == OffsetType::ABS) {
            styleYOff = styleYOff * DPMM / _score->spatium();
            }

      // TODO: check correct dy handling
      // previous code: double dy = -0.1 * e.attribute("default-y", QString::number(styleYOff* -10)).toDouble();
      double dy = -0.1 * _e.attributes().value("default-y").toDouble();

      bool printObject = _e.attributes().value("print-object") != "no";
      QString printFrame = _e.attributes().value("print-frame").toString();
      QString printStyle = _e.attributes().value("print-style").toString();

      QString kind, kindText, symbols, parens;
      QList<HDegree> degreeList;

      /* TODO ?
      if (harmony) {
            qDebug("MusicXML::import: more than one harmony");
            return;
      }
       */

      FretDiagram* fd = 0;
      Harmony* ha = new Harmony(_score);
      ha->setUserOff(QPointF(rx, ry + dy - styleYOff));
      Fraction offset;
      while (_e.readNextStartElement()) {
            if (_e.name() == "root") {
                  QString step;
                  int alter = 0;
                  bool invalidRoot = false;
                  while (_e.readNextStartElement()) {
                        if (_e.name() == "root-step") {
                              // attributes: print-style
                              step = _e.readElementText();
                              /* TODO: check if this is required
                              if (ee.hasAttribute("text")) {
                                    QString rtext = ee.attribute("text");
                                    if (rtext == "") {
                                          invalidRoot = true;
                                    }
                              }
                               */
                              }
                        else if (_e.name() == "root-alter") {
                              // attributes: print-object, print-style
                              //             location (left-right)
                              alter = _e.readElementText().toInt();
                              }
                        else
                              skipLogCurrElem();
                        }
                  if (invalidRoot)
                        ha->setRootTpc(Tpc::TPC_INVALID);
                  else
                        ha->setRootTpc(step2tpc(step, AccidentalVal(alter)));
                  }
            else if (_e.name() == "function") {
                  // attributes: print-style
                  skipLogCurrElem();
                  }
            else if (_e.name() == "kind") {
                  // attributes: use-symbols  yes-no
                  //             text, stack-degrees, parentheses-degree, bracket-degrees,
                  //             print-style, halign, valign

                  kindText = _e.attributes().value("text").toString();
                  symbols = _e.attributes().value("use-symbols").toString();
                  parens = _e.attributes().value("parentheses-degrees").toString();
                  kind = _e.readElementText();
                  }
            else if (_e.name() == "inversion") {
                  // attributes: print-style
                  skipLogCurrElem();
                  }
            else if (_e.name() == "bass") {
                  QString step;
                  int alter = 0;
                  while (_e.readNextStartElement()) {
                        if (_e.name() == "bass-step") {
                              // attributes: print-style
                              step = _e.readElementText();
                              }
                        else if (_e.name() == "bass-alter") {
                              // attributes: print-object, print-style
                              //             location (left-right)
                              alter = _e.readElementText().toInt();
                              }
                        else
                              skipLogCurrElem();
                        }
                  ha->setBaseTpc(step2tpc(step, AccidentalVal(alter)));
                  }
            else if (_e.name() == "degree") {
                  int degreeValue = 0;
                  int degreeAlter = 0;
                  QString degreeType = "";
                  while (_e.readNextStartElement()) {
                        if (_e.name() == "degree-value") {
                              degreeValue = _e.readElementText().toInt();
                              }
                        else if (_e.name() == "degree-alter") {
                              degreeAlter = _e.readElementText().toInt();
                              }
                        else if (_e.name() == "degree-type") {
                              degreeType = _e.readElementText();
                              }
                        else
                              skipLogCurrElem();
                        }
                  if (degreeValue <= 0 || degreeValue > 13
                      || degreeAlter < -2 || degreeAlter > 2
                      || (degreeType != "add" && degreeType != "alter" && degreeType != "subtract")) {
                        _logger->logError(QString("incorrect degree: degreeValue=%1 degreeAlter=%2 degreeType=%3")
                                          .arg(degreeValue).arg(degreeAlter).arg(degreeType), &_e);
                        }
                  else {
                        if (degreeType == "add")
                              degreeList << HDegree(degreeValue, degreeAlter, HDegreeType::ADD);
                        else if (degreeType == "alter")
                              degreeList << HDegree(degreeValue, degreeAlter, HDegreeType::ALTER);
                        else if (degreeType == "subtract")
                              degreeList << HDegree(degreeValue, degreeAlter, HDegreeType::SUBTRACT);
                        }
                  }
            else if (_e.name() == "frame")
                  fd = frame();
            else if (_e.name() == "level")
                  skipLogCurrElem();
            else if (_e.name() == "offset")
                  offset = calcTicks(_e.readElementText(), _divs);
            else if (_e.name() == "staff") {
                  int nstaves = _pass1.getPart(partId)->nstaves();
                  QString strStaff = _e.readElementText();
                  int staff = strStaff.toInt();
                  if (0 < staff && staff <= nstaves)
                        track += (staff - 1) * VOICES;
                  else
                        _logger->logError(QString("invalid staff %1").arg(strStaff), &_e);
                  }
            else
                  skipLogCurrElem();
            }

      if (fd) {
            fd->setTrack(track);
            Segment* s = measure->getSegment(Segment::Type::ChordRest, (sTime + offset).ticks());
            s->add(fd);
            }

      const ChordDescription* d = 0;
      if (ha->rootTpc() != Tpc::TPC_INVALID)
            d = ha->fromXml(kind, kindText, symbols, parens, degreeList);
      if (d) {
            ha->setId(d->id);
            ha->setTextName(d->names.front());
            }
      else {
            ha->setId(-1);
            ha->setTextName(kindText);
            }
      ha->render();

      ha->setVisible(printObject);

      // TODO-LV: do this only if ha points to a valid harmony
      // harmony = ha;
      ha->setTrack(track);
      Segment* s = measure->getSegment(Segment::Type::ChordRest, (sTime + offset).ticks());
      s->add(ha);
      }

//---------------------------------------------------------
//   beam
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/beam node.
 Sets beamMode in case of begin, continue or end beam number 1.
 */

void MusicXMLParserPass2::beam(Beam::Mode& beamMode)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "beam");

      int beamNo = _e.attributes().value("number").toInt();

      if (beamNo == 1) {
            QString s = _e.readElementText();
            if (s == "begin")
                  beamMode = Beam::Mode::BEGIN;
            else if (s == "end")
                  beamMode = Beam::Mode::END;
            else if (s == "continue")
                  beamMode = Beam::Mode::MID;
            else if (s == "backward hook")
                  ;
            else if (s == "forward hook")
                  ;
            else
                  _logger->logError(QString("unknown beam keyword '%1'").arg(s), &_e);
            }
      else
            _e.skipCurrentElement();
      }

//---------------------------------------------------------
//   forward
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/forward node.
 */

void MusicXMLParserPass2::forward(Fraction& dura)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "forward");

      while (_e.readNextStartElement()) {
            if (_e.name() == "duration")
                  duration(dura);
            else if (_e.name() == "staff")
                  _e.skipCurrentElement();  // skip but don't log
            else if (_e.name() == "voice")
                  _e.skipCurrentElement();  // skip but don't log
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   backup
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/backup node.
 */

void MusicXMLParserPass2::backup(Fraction& dura)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "backup");

      while (_e.readNextStartElement()) {
            if (_e.name() == "duration")
                  duration(dura);
            else
                  skipLogCurrElem();
            }
      }

//---------------------------------------------------------
//   lyric -- parse a MusicXML lyric element
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/lyric node.
 */

void MusicXMLParserPass2::lyric(const QString& partId,
                                QMap<int, Lyrics*>& numbrdLyrics,
                                QSet<Lyrics*>& extLyrics)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "lyric");

      Lyrics* l = new Lyrics(_score);
      // TODO in addlyrics: l->setTrack(trk);

      bool hasExtend = false;
      QString lyricNumber = _e.attributes().value("number").toString();
      QColor lyricColor = QColor::Invalid;
      lyricColor.setNamedColor(_e.attributes().value("color").toString());
      QString extendType;
      QString formattedText;

      while (_e.readNextStartElement()) {
            if (_e.name() == "elision") {
                  // TODO verify elision handling
                  /*
                   QString text = _e.readElementText();
                   if (text.isEmpty())
                   formattedText += " ";
                   else
                   */
                  formattedText += nextPartOfFormattedString(_e);
                  }
            else if (_e.name() == "extend") {
                  hasExtend = true;
                  extendType = _e.attributes().value("type").toString();
                  _e.readNext();
                  }
            else if (_e.name() == "syllabic") {
                  QString syll = _e.readElementText();
                  if (syll == "single")
                        l->setSyllabic(Lyrics::Syllabic::SINGLE);
                  else if (syll == "begin")
                        l->setSyllabic(Lyrics::Syllabic::BEGIN);
                  else if (syll == "end")
                        l->setSyllabic(Lyrics::Syllabic::END);
                  else if (syll == "middle")
                        l->setSyllabic(Lyrics::Syllabic::MIDDLE);
                  else
                        qDebug("unknown syllabic %s", qPrintable(syll));  // TODO
                  }
            else if (_e.name() == "text")
                  formattedText += nextPartOfFormattedString(_e);
            else
                  skipLogCurrElem();
            }

      // if no lyric read (e.g. only 'extend "type=stop"'), no further action required
      if (formattedText == "") {
            delete l;
            return;
            }

      auto mxmlPart = _pass1.getMusicXmlPart(partId);
      auto lyricNo = mxmlPart.lyricNumberHandler().getLyricNo(lyricNumber);
      if (lyricNo < 0) {
            _logger->logError("invalid lyrics number (<0)", &_e);
            delete l;
            return;
            }
      else if (lyricNo > MAX_LYRICS) {
            _logger->logError(QString("too much lyrics (>%1)").arg(MAX_LYRICS), &_e);
            delete l;
            return;
            }
      else if (numbrdLyrics.contains(lyricNo)) {
            _logger->logError(QString("duplicate lyrics number (%1)").arg(lyricNumber), &_e);
            delete l;
            return;
            }

      numbrdLyrics[lyricNo] = l;

      if (hasExtend && (extendType == "" || extendType == "start"))
            extLyrics.insert(l);

      //qDebug("formatted lyric '%s'", qPrintable(formattedText));
      l->setXmlText(formattedText);
      if (lyricColor != QColor::Invalid)
            l->setColor(lyricColor);
      }

//---------------------------------------------------------
//   slur
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/slur node.
 */

void MusicXMLParserPass2::slur(ChordRest* cr, const int tick, const int track, bool& lastGraceAFter)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "slur");

      int slurNo   = _e.attributes().value("number").toString().toInt();
      if (slurNo > 0) slurNo--;
      QString slurType = _e.attributes().value("type").toString();
      QString lineType  = _e.attributes().value("line-type").toString();
      if (lineType == "") lineType = "solid";

      // PriMus Music-Notation by Columbussoft (build 10093) generates overlapping
      // slurs that do not have a number attribute to distinguish them.
      // The duplicates must be ignored, to prevent memory allocation issues,
      // which caused a MuseScore crash
      // Similar issues happen with Sibelius 7.1.3 (direct export)

      if (slurType == "start") {
            if (_slurs[slurNo].isStart())
                  // slur start when slur already started: report error
                  _logger->logError(QString("ignoring duplicate slur start"), &_e);
            else if (_slurs[slurNo].isStop()) {
                  // slur start when slur already stopped: wrap up
                  Slur* newSlur = _slurs[slurNo].slur();
                  newSlur->setTick(tick);
                  newSlur->setStartElement(cr);
                  _slurs[slurNo] = SlurDesc();
                  }
            else {
                  // slur start for new slur: init
                  Slur* newSlur = new Slur(_score);
                  if (cr->isGrace())
                        newSlur->setAnchor(Spanner::Anchor::CHORD);
                  if (lineType == "dotted")
                        newSlur->setLineType(1);
                  else if (lineType == "dashed")
                        newSlur->setLineType(2);
                  newSlur->setTick(tick);
                  newSlur->setStartElement(cr);
                  QString pl = _e.attributes().value("placement").toString();
                  if (pl == "above")
                        newSlur->setSlurDirection(MScore::Direction::UP);
                  else if (pl == "below")
                        newSlur->setSlurDirection(MScore::Direction::DOWN);
                  newSlur->setTrack(track);
                  newSlur->setTrack2(track);
                  _slurs[slurNo].start(newSlur);
                  _score->addElement(newSlur);
                  }
            }
      else if (slurType == "stop") {
            if (_slurs[slurNo].isStart()) {
                  // slur stop when slur already started: wrap up
                  Slur* newSlur = _slurs[slurNo].slur();
                  if (!(cr->isGrace())) {
                        newSlur->setTick2(tick);
                        newSlur->setTrack2(track);
                        }
                  newSlur->setEndElement(cr);
                  _slurs[slurNo] = SlurDesc();
                  }
            else if (_slurs[slurNo].isStop())
                  // slur stop when slur already stopped: report error
                  _logger->logError(QString("ignoring duplicate slur stop"), &_e);
            else {
                  // slur stop for new slur: init
                  Slur* newSlur = new Slur(_score);
                  if (!(cr->isGrace())) {
                        newSlur->setTick2(tick);
                        newSlur->setTrack2(track);
                        }
                  newSlur->setEndElement(cr);
                  _slurs[slurNo].stop(newSlur);
                  }
            // any grace note containing a slur stop means
            // last note of a grace after set has been found
            if (cr->isGrace())
                  lastGraceAFter = true;
            }
      else if (slurType == "continue")
            ;              // ignore
      else
            _logger->logError(QString("unknown slur type %1").arg(slurType), &_e);

      _e.readNext();
      }

//---------------------------------------------------------
//   tied
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/tied node.
 */

void MusicXMLParserPass2::tied(Note* note, const int track)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "tied");

      QString tiedType = _e.attributes().value("type").toString();
      if (tiedType == "start") {
            if (_tie) {
                  _logger->logError(QString("Tie already active"), &_e);
                  }
            else if (note) {
                  _tie = new Tie(_score);
                  note->setTieFor(_tie);
                  _tie->setStartNote(note);
                  _tie->setTrack(track);
                  QString tiedOrientation = _e.attributes().value("orientation").toString();
                  if (tiedOrientation == "over")
                        _tie->setSlurDirection(MScore::Direction::UP);
                  else if (tiedOrientation == "under")
                        _tie->setSlurDirection(MScore::Direction::DOWN);
                  else if (tiedOrientation == "auto")
                        ;              // ignore
                  else if (tiedOrientation == "")
                        ;              // ignore
                  else
                        _logger->logError(QString("unknown tied orientation: %1").arg(tiedOrientation), &_e);

                  QString lineType  = _e.attributes().value("line-type").toString();
                  if (lineType == "dotted")
                        _tie->setLineType(1);
                  else if (lineType == "dashed")
                        _tie->setLineType(2);
                  _tie = 0;
                  }
            }
      else if (tiedType == "stop")
            ;              // ignore
      else
            _logger->logError(QString("unknown tied type %").arg(tiedType), &_e);

      _e.readNext();
      }

//---------------------------------------------------------
//   dynamics
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/dynamics node.
 */

void MusicXMLParserPass2::dynamics(QString& placement, QStringList& dynamicslist)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "dynamics");

      placement = _e.attributes().value("placement").toString();
      if (preferences.musicxmlImportLayout) {
            // ry        = ee.attribute(QString("relative-y"), "0").toDouble() * -.1;
            // rx        = ee.attribute(QString("relative-x"), "0").toDouble() * .1;
            // yoffset   = _e.attributes().value("default-y").toDouble(&hasYoffset) * -0.1;
            // xoffset   = ee.attribute("default-x", "0.0").toDouble() * 0.1;
            }
      while (_e.readNextStartElement()) {
            if (_e.name() == "other-dynamics")
                  dynamicslist.push_back(_e.readElementText());
            else {
                  dynamicslist.push_back(_e.name().toString());
                  _e.readNext();
                  }
            }
      }

//---------------------------------------------------------
//   articulations
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/articulations node.
 Note that some notations attach to notes only in MuseScore,
 which means trying to attach them to a rest will crash,
 as in that case note is 0.
 */

void MusicXMLParserPass2::articulations(ChordRest* cr, int& breath, QString& chordLineType)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "articulations");

      while (_e.readNextStartElement()) {
            if (addMxmlArticulationToChord(cr, _e.name().toString())) {
                  _e.readNext();
                  continue;
                  }
            else if (_e.name() == "breath-mark") {
                  breath = 0;
                  _e.readElementText();
                  // TODO: handle value read (note: encoding unknown, only "comma" found)
                  }
            else if (_e.name() == "caesura") {
                  breath = 3;
                  _e.readNext();
                  }
            else if (_e.name() == "doit"
                     || _e.name() == "falloff"
                     || _e.name() == "plop"
                     || _e.name() == "scoop") {
                  chordLineType = _e.name().toString();
                  _e.readNext();
                  }
            else if (_e.name() == "strong-accent") {
                  QString strongAccentType = _e.attributes().value("type").toString();
                  if (strongAccentType == "up" || strongAccentType == "")
                        addArticulationToChord(cr, ArticulationType::Marcato, "up");
                  else if (strongAccentType == "down")
                        addArticulationToChord(cr, ArticulationType::Marcato, "down");
                  else
                        _logger->logError(QString("unknown mercato type %1").arg(strongAccentType), &_e);
                  _e.readNext();
                  }
            else
                  skipLogCurrElem();
            }
      //qDebug("::notations tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));
      }

//---------------------------------------------------------
//   ornaments
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/ornaments node.
 */

void MusicXMLParserPass2::ornaments(ChordRest* cr,
                                    QString& wavyLineType,
                                    int& wavyLineNo,
                                    QString& tremoloType,
                                    int& tremoloNr, bool& lastGraceAFter)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "ornaments");

      bool trillMark = false;
      // <trill-mark placement="above"/>
      while (_e.readNextStartElement()) {
            if (addMxmlArticulationToChord(cr, _e.name().toString())) {
                  _e.readNext();
                  continue;
                  }
            else if (_e.name() == "trill-mark") {
                  trillMark = true;
                  _e.readNext();
                  }
            else if (_e.name() == "wavy-line") {
                  wavyLineType = _e.attributes().value("type").toString();
                  wavyLineNo   = _e.attributes().value("number").toString().toInt();
                  if (wavyLineNo > 0) wavyLineNo--;
                  // any grace note containing a wavy-line stop means
                  // last note of a grace after set has been found
                  if (wavyLineType == "stop" && cr->isGrace())
                        lastGraceAFter = true;
                  _e.readNext();
                  }
            else if (_e.name() == "tremolo") {
                  tremoloType = _e.attributes().value("type").toString();
                  tremoloNr = _e.readElementText().toInt();
                  }
            else if (_e.name() == "accidental-mark")
                  skipLogCurrElem();
            else if (_e.name() == "delayed-turn") {
                  // TODO: actually this should be offset a bit to the right
                  addArticulationToChord(cr, ArticulationType::Turn, "");
                  _e.readNext();
                  }
            else if (_e.name() == "inverted-mordent"
                     || _e.name() == "mordent") {
                  addMordentToChord(cr, _e.name().toString(),
                                    _e.attributes().value("long").toString(),
                                    _e.attributes().value("approach").toString(),
                                    _e.attributes().value("departure").toString());
                  _e.readNext();
                  }
            else
                  skipLogCurrElem();
            }
      //qDebug("::notations tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));
      // note that mscore wavy line already implicitly includes a trillsym
      // so don't add an additional one
      if (trillMark && wavyLineType != "start")
            addArticulationToChord(cr, ArticulationType::Trill, "");
      }

//---------------------------------------------------------
//   technical
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/technical node.
 */

void MusicXMLParserPass2::technical(Note* note, ChordRest* cr)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "technical");

      while (_e.readNextStartElement()) {
            if (addMxmlArticulationToChord(cr, _e.name().toString())) {
                  _e.readNext();
                  continue;
                  }
            else if (_e.name() == "fingering")
                  // TODO: distinguish between keyboards (style TextStyleType::FINGERING)
                  // and (plucked) strings (style TextStyleType::LH_GUITAR_FINGERING)
                  addTextToNote(_e.lineNumber(), _e.columnNumber(), _e.readElementText(),
                                TextStyleType::FINGERING, _score, note);
            else if (_e.name() == "fret") {
                  int fret = _e.readElementText().toInt();
                  if (note) {
                        if (note->staff()->isTabStaff())
                              note->setFret(fret);
                        }
                  else
                        _logger->logError("no note for fret", &_e);
                  }
            else if (_e.name() == "pluck")
                  addTextToNote(_e.lineNumber(), _e.columnNumber(), _e.readElementText(),
                                TextStyleType::RH_GUITAR_FINGERING, _score, note);
            else if (_e.name() == "string") {
                  QString txt = _e.readElementText();
                  if (note) {
                        if (note->staff()->isTabStaff())
                              note->setString(txt.toInt() - 1);
                        else
                              addTextToNote(_e.lineNumber(), _e.columnNumber(), txt,
                                            TextStyleType::STRING_NUMBER, _score, note);
                        }
                  else
                        _logger->logError("no note for string", &_e);
                  }
            else if (_e.name() == "pull-off")
                  skipLogCurrElem();
            else
                  skipLogCurrElem();
            }
      //qDebug("::notations tokenString '%s' name '%s'", qPrintable(_e.tokenString()), qPrintable(_e.name().toString()));
      }

//---------------------------------------------------------
//   glissando
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/glissando
 and /score-partwise/part/measure/note/notations/slide nodes.
 */

void MusicXMLParserPass2::glissando(Note* note, const int tick, const int ticks, const int track)
      {
      Q_ASSERT(_e.isStartElement() && (_e.name() == "glissando" || _e.name() == "slide"));

      int n                   = _e.attributes().value("number").toString().toInt();
      if (n > 0) n--;
      QString spannerType     = _e.attributes().value("type").toString();
      int tag                 = _e.name() == "slide" ? 0 : 1;
      //                  QString lineType  = ee.attribute(QString("line-type"), "solid");
      Glissando*& gliss = _glissandi[n][tag];
      if (spannerType == "start") {
            QColor color(_e.attributes().value("color").toString());
            QString glissText = _e.readElementText();
            if (gliss) {
                  _logger->logError(QString("overlapping glissando/slide number %1").arg(n+1), &_e);
                  }
            else if (!note) {
                  _logger->logError(QString("no note for glissando/slide number %1 start").arg(n+1), &_e);
                  }
            else {
                  gliss = new Glissando(_score);
                  gliss->setAnchor(Spanner::Anchor::NOTE);
                  gliss->setStartElement(note);
                  gliss->setTick(tick);
                  gliss->setTrack(track);
                  gliss->setParent(note);
                  if (color.isValid())
                        gliss->setColor(color);
                  gliss->setText(glissText);
                  gliss->setGlissandoType(tag == 0 ? Glissando::Type::STRAIGHT : Glissando::Type::WAVY);
                  _spanners[gliss] = QPair<int, int>(tick, -1);
                  // qDebug("glissando/slide=%p inserted at first tick %d", gliss, tick);
                  }
            }
      else if (spannerType == "stop") {
            if (!gliss) {
                  _logger->logError(QString("glissando/slide number %1 stop without start").arg(n+1), &_e);
                  }
            else if (!note) {
                  _logger->logError(QString("no note for glissando/slide number %1 stop").arg(n+1), &_e);
                  }
            else {
                  _spanners[gliss].second = tick + ticks;
                  gliss->setEndElement(note);
                  gliss->setTick2(tick);
                  gliss->setTrack2(track);
                  // qDebug("glissando/slide=%p second tick %d", gliss, tick);
                  gliss = 0;
                  }
            }
      else
            _logger->logError(QString("unknown glissando/slide type %1").arg(spannerType), &_e);
      _e.readNext();
      }

//---------------------------------------------------------
//   addArpeggio
//---------------------------------------------------------

static void addArpeggio(ChordRest* cr, const QString& arpeggioType,
                        MxmlLogger* logger, const QXmlStreamReader* const xmlreader)
      {
      // no support for arpeggio on rest
      if (!arpeggioType.isEmpty() && cr->type() == Element::Type::CHORD) {
            Arpeggio* a = new Arpeggio(cr->score());
            if (arpeggioType == "none")
                  a->setArpeggioType(ArpeggioType::NORMAL);
            else if (arpeggioType == "up")
                  a->setArpeggioType(ArpeggioType::UP);
            else if (arpeggioType == "down")
                  a->setArpeggioType(ArpeggioType::DOWN);
            else if (arpeggioType == "non-arpeggiate")
                  a->setArpeggioType(ArpeggioType::BRACKET);
            else {
                  logger->logError(QString("unknown arpeggio type %1").arg(arpeggioType), xmlreader);
                  delete a;
                  a = 0;
                  }
            if ((static_cast<Chord*>(cr))->arpeggio()) {
                  // there can be only one
                  delete a;
                  a = 0;
                  }
            else
                  cr->add(a);
            }
      }

//---------------------------------------------------------
//   addTremolo
//---------------------------------------------------------

static void addTremolo(ChordRest* cr,
                       const int tremoloNr, const QString& tremoloType, const int ticks,
                       Chord*& tremStart,
                       MxmlLogger* logger, const QXmlStreamReader* const xmlreader)
      {
      if (cr->type() != Element::Type::CHORD)
            return;
      if (tremoloNr) {
            //qDebug("tremolo %d type '%s' ticks %d tremStart %p", tremoloNr, qPrintable(tremoloType), ticks, _tremStart);
            if (tremoloNr == 1 || tremoloNr == 2 || tremoloNr == 3 || tremoloNr == 4) {
                  if (tremoloType == "" || tremoloType == "single") {
                        Tremolo* t = new Tremolo(cr->score());
                        switch (tremoloNr) {
                              case 1: t->setTremoloType(TremoloType::R8); break;
                              case 2: t->setTremoloType(TremoloType::R16); break;
                              case 3: t->setTremoloType(TremoloType::R32); break;
                              case 4: t->setTremoloType(TremoloType::R64); break;
                              }
                        cr->add(t);
                        }
                  else if (tremoloType == "start") {
                        if (tremStart) logger->logError("MusicXML::import: double tremolo start", xmlreader);
                        tremStart = static_cast<Chord*>(cr);
                        }
                  else if (tremoloType == "stop") {
                        if (tremStart) {
                              Tremolo* t = new Tremolo(cr->score());
                              switch (tremoloNr) {
                                    case 1: t->setTremoloType(TremoloType::C8); break;
                                    case 2: t->setTremoloType(TremoloType::C16); break;
                                    case 3: t->setTremoloType(TremoloType::C32); break;
                                    case 4: t->setTremoloType(TremoloType::C64); break;
                                    }
                              t->setChords(tremStart, static_cast<Chord*>(cr));
                              // fixup chord duration and type
                              const int tremDur = ticks / 2;
                              t->chord1()->setDurationType(tremDur);
                              t->chord1()->setDuration(Fraction::fromTicks(tremDur));
                              t->chord2()->setDurationType(tremDur);
                              t->chord2()->setDuration(Fraction::fromTicks(tremDur));
                              // add tremolo to first chord (only)
                              tremStart->add(t);
                              }
                        else logger->logError("MusicXML::import: double tremolo stop w/o start", xmlreader);
                        tremStart = 0;
                        }
                  }
            else
                  logger->logError(QString("unknown tremolo type %1").arg(tremoloNr), xmlreader);
            }
      }

//---------------------------------------------------------
//   addWavyLine
//---------------------------------------------------------

static void addWavyLine(ChordRest* cr, const int tick,
                        const int wavyLineNo, const QString& wavyLineType,
                        MusicXmlSpannerMap& spanners, TrillStack& trills,
                        MxmlLogger* logger, const QXmlStreamReader* const xmlreader)
      {
      if (!wavyLineType.isEmpty()) {
            const auto ticks = cr->duration().ticks();
            const auto track = cr->track();
            const auto trk = (track / VOICES) * VOICES;             // first track of staff
            Trill*& t = trills[wavyLineNo];
            if (wavyLineType == "start") {
                  if (t) {
                        logger->logError(QString("overlapping wavy-line number %1").arg(wavyLineNo+1), xmlreader);
                        }
                  else {
                        t = new Trill(cr->score());
                        t->setTrack(trk);
                        spanners[t] = QPair<int, int>(tick, -1);
                        // qDebug("wedge trill=%p inserted at first tick %d", trill, tick);
                        }
                  }
            else if (wavyLineType == "stop") {
                  if (!t) {
                        logger->logError(QString("wavy-line number %1 stop without start").arg(wavyLineNo+1), xmlreader);
                        }
                  else {
                        spanners[t].second = tick + ticks;
                        // qDebug("wedge trill=%p second tick %d", trill, tick);
                        t = 0;
                        }
                  }
            else
                  logger->logError(QString("unknown wavy-line type %1").arg(wavyLineType), xmlreader);
            }
      }

//---------------------------------------------------------
//   addBreath
//---------------------------------------------------------

static void addBreath(ChordRest* cr, const int tick, const int breath)
      {
      if (breath >= 0 && !cr->isGrace()) {
            Breath* b = new Breath(cr->score());
            // b->setTrack(trk + voice); TODO check next line
            b->setTrack(cr->track());
            b->setBreathType(breath);
            const auto ticks = cr->duration().ticks();
            auto seg = cr->measure()->getSegment(Segment::Type::Breath, tick + ticks);
            seg->add(b);
            }
      }

//---------------------------------------------------------
//   addChordLine
//---------------------------------------------------------

static void addChordLine(Note* note, const QString& chordLineType,
                         MxmlLogger* logger, const QXmlStreamReader* const xmlreader)
      {
      if (chordLineType != "") {
            if (note) {
                  ChordLine* cl = new ChordLine(note->score());
                  if (chordLineType == "falloff")
                        cl->setChordLineType(ChordLineType::FALL);
                  if (chordLineType == "doit")
                        cl->setChordLineType(ChordLineType::DOIT);
                  if (chordLineType == "plop")
                        cl->setChordLineType(ChordLineType::PLOP);
                  if (chordLineType == "scoop")
                        cl->setChordLineType(ChordLineType::SCOOP);
                  note->chord()->add(cl);
                  }
            else
                  logger->logError(QString("no note for %1").arg(chordLineType), xmlreader);
            }
      }

//---------------------------------------------------------
//   notations
//---------------------------------------------------------


/**
 Parse the /score-partwise/part/measure/note/notations node.
 Note that some notations attach to notes only in MuseScore,
 which means trying to attach them to a rest will crash,
 as in that case note is 0.
 */

void MusicXMLParserPass2::notations(Note* note, ChordRest* cr, const int tick,
                                    MusicXmlTupletDesc& tupletDesc, bool& lastGraceAFter)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "notations");
      if (cr) {
            lastGraceAFter = false; // ensure default

            Measure* measure = cr->measure();
            int ticks = cr->duration().ticks();
            int track = cr->track();

            QString wavyLineType;
            int wavyLineNo = 0;
            QString arpeggioType;
            int breath = -1;
            int tremoloNr = 0;
            QString tremoloType;
            QString placement;
            QStringList dynamicslist;
            // qreal rx = 0.0;
            // qreal ry = 0.0;
            qreal yoffset = 0.0; // actually this is default-y
            // qreal xoffset = 0.0; // not used
            bool hasYoffset = false;
            QString chordLineType;

            while (_e.readNextStartElement()) {
                  if (_e.name() == "slur") {
                        slur(cr, tick, track, lastGraceAFter);
                        }
                  else if (_e.name() == "tied") {
                        tied(note, track);
                        }
                  else if (_e.name() == "tuplet") {
                        tuplet(tupletDesc);
                        }
                  else if (_e.name() == "dynamics") {
                        placement = _e.attributes().value("placement").toString();
                        if (preferences.musicxmlImportLayout) {
                              // ry        = ee.attribute(QString("relative-y"), "0").toDouble() * -.1;
                              // rx        = ee.attribute(QString("relative-x"), "0").toDouble() * .1;
                              yoffset   = _e.attributes().value("default-y").toDouble(&hasYoffset) * -0.1;
                              // xoffset   = ee.attribute("default-x", "0.0").toDouble() * 0.1;
                              }
                        dynamics(placement, dynamicslist);
                        }
                  else if (_e.name() == "articulations") {
                        articulations(cr, breath, chordLineType);
                        }
                  else if (_e.name() == "fermata")
                        fermata(cr);
                  else if (_e.name() == "ornaments") {
                        ornaments(cr, wavyLineType, wavyLineNo, tremoloType, tremoloNr, lastGraceAFter);
                        }
                  else if (_e.name() == "technical") {
                        technical(note, cr);
                        }
                  else if (_e.name() == "arpeggiate") {
                        arpeggioType = _e.attributes().value("direction").toString();
                        if (arpeggioType == "") arpeggioType = "none";
                        _e.readNext();
                        }
                  else if (_e.name() == "non-arpeggiate") {
                        arpeggioType = "non-arpeggiate";
                        _e.readNext();
                        }
                  else if (_e.name() == "glissando" || _e.name() == "slide") {
                        glissando(note, tick, ticks, track);
                        }
                  else
                        skipLogCurrElem();
                  }

            addArpeggio(cr, arpeggioType, _logger, &_e);
            addWavyLine(cr, tick, wavyLineNo, wavyLineType, _spanners, _trills, _logger, &_e);
            addBreath(cr, tick, breath);
            addTremolo(cr, tremoloNr, tremoloType, ticks, _tremStart, _logger, &_e);
            addChordLine(note, chordLineType, _logger, &_e);

            // more than one dynamic ???
            // LVIFIX: check import/export of <other-dynamics>unknown_text</...>
            // TODO remove duplicate code (see MusicXml::direction)
            for (QStringList::Iterator it = dynamicslist.begin(); it != dynamicslist.end(); ++it ) {
                  Dynamic* dyn = new Dynamic(_score);
                  dyn->setDynamicType(*it);
                  if (hasYoffset) dyn->textStyle().setYoff(yoffset);
                  addElemOffset(dyn, track, placement, measure, tick);
                  }
            }
      else {
            _logger->logDebugInfo("no note to attach to, skipping notations", &_e);
            _e.skipCurrentElement();
            }

      Q_ASSERT(_e.isEndElement() && _e.name() == "notations");
      }

//---------------------------------------------------------
//   stem
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/stem node.
 */

void MusicXMLParserPass2::stem(MScore::Direction& sd, bool& nost)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "stem");

      // defaults
      sd = MScore::Direction::AUTO;
      nost = false;

      QString s = _e.readElementText();

      if (s == "up")
            sd = MScore::Direction::UP;
      else if (s == "down")
            sd = MScore::Direction::DOWN;
      else if (s == "none")
            nost = true;
      else if (s == "double")
            ;
      else
            _logger->logError(QString("unknown stem direction %1").arg(s), &_e);
      }

//---------------------------------------------------------
//   fermata
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/fermata node.
 Note: MusicXML common.mod: "An empty fermata element represents a normal fermata."
 */

void MusicXMLParserPass2::fermata(ChordRest* cr)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "fermata");

      QString fermataType = _e.attributes().value("type").toString();
      QString fermata     = _e.readElementText();

      if (fermata == "normal" || fermata == "")
            addFermata(cr, fermataType, ArticulationType::Fermata);
      else if (fermata == "angled")
            addFermata(cr, fermataType, ArticulationType::Shortfermata);
      else if (fermata == "square")
            addFermata(cr, fermataType, ArticulationType::Longfermata);
      else
            _logger->logError(QString("unknown fermata '%1'").arg(fermata), &_e);
      }

//---------------------------------------------------------
//   tuplet
//---------------------------------------------------------

/**
 Parse the /score-partwise/part/measure/note/notations/tuplet node.
 */

void MusicXMLParserPass2::tuplet(MusicXmlTupletDesc& tupletDesc)
      {
      Q_ASSERT(_e.isStartElement() && _e.name() == "tuplet");

      QString tupletType       = _e.attributes().value("type").toString();
      // QString tupletPlacement  = _e.attributes().value("placement").toString(); not used (TODO)
      QString tupletBracket    = _e.attributes().value("bracket").toString();
      QString tupletShowNumber = _e.attributes().value("show-number").toString();

      // ignore possible children (currently not supported)
      _e.skipCurrentElement();

      if (tupletType == "start")
            tupletDesc.type = MxmlStartStop::START;
      else if (tupletType == "stop")
            tupletDesc.type = MxmlStartStop::STOP;
      else if (tupletType != "" && tupletType != "start" && tupletType != "stop") {
            _logger->logError(QString("unknown tuplet type '%1'").arg(tupletType), &_e);
            }

      // set bracket, leave at default if unspecified
      if (tupletBracket == "yes")
            tupletDesc.bracket = Tuplet::BracketType::SHOW_BRACKET;
      else if (tupletBracket == "no")
            tupletDesc.bracket = Tuplet::BracketType::SHOW_NO_BRACKET;

      // set number, default is "actual" (=NumberType::SHOW_NUMBER)
      if (tupletShowNumber == "both")
            tupletDesc.shownumber = Tuplet::NumberType::SHOW_RELATION;
      else if (tupletShowNumber == "none")
            tupletDesc.shownumber = Tuplet::NumberType::NO_TEXT;
      else
            tupletDesc.shownumber = Tuplet::NumberType::SHOW_NUMBER;
      }

//---------------------------------------------------------
//   MusicXMLParserDirection
//---------------------------------------------------------

/**
 MusicXMLParserDirection constructor.
 */

MusicXMLParserDirection::MusicXMLParserDirection(QXmlStreamReader& e,
                                                 Score* score,
                                                 const MusicXMLParserPass1& pass1,
                                                 MusicXMLParserPass2& pass2,
                                                 MxmlLogger* logger)
      : _e(e), _score(score), _pass1(pass1), _pass2(pass2), _logger(logger),
      _hasDefaultY(false), _defaultY(0.0), _coda(false), _segno(false),
      _tpoMetro(0), _tpoSound(0)
      {
      // nothing
      }

}