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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

import {WHOLE_DURATION_MAGNITUDE, FractionNumber, lcmMulti, gcd, MAIN_SCORE_NAME} from "./utils";
import * as idioms from "./idioms";
import {LILYPOND_VERSION} from "../constants";
import * as measureLayout from "../measureLayout";
import ImplicitType from "../lilyNotation/implicitType";
import pick from "../pick";



interface Location {
	lines: [number, number];
	columns: [number, number];
};


abstract class Locator {
	location: Location;


	constructor (term: BaseTerm) {
		term._location = term._location || {lines: [0, 0], columns: [0, 0]};
		this.location = term._location;
	}

	abstract set (line: number, column: number): void;
};


class OpenLocator extends Locator {
	set (line: number, column: number) {
		this.location.lines[0] = line;
		this.location.columns[0] = column;
	}
};


class CloseLocator extends Locator {
	set (line: number, column: number) {
		this.location.lines[1] = line;
		this.location.columns[1] = column;
	}
};


// concat array of array
const cc = <T>(arrays: T[][]): T[] => [].concat(...arrays);


export class MusicChunk {
	parent: MusicBlock;
	terms: BaseTerm[];


	static join (chunks: MusicChunk[]): BaseTerm[] {
		return cc(chunks.map((chunk, i) => i === chunks.length - 1 ? chunk.terms : [...chunk.terms, new Divide({})]));
	}


	constructor (parent: MusicBlock, terms: BaseTerm[] = []) {
		this.parent = parent;
		this.terms = terms;
	}


	push (term: BaseTerm) {
		this.terms.push(term);
	}


	get size () {
		return this.terms.length;
	}


	get durationMagnitude () {
		return this.terms.reduce((magnitude, term) => magnitude + term.durationMagnitude, 0);
	}
};


interface MusicVoice {
	name?: string;
	body: MusicChunk[];
};


type MusicChunkMap = Map<number, MusicChunk>;


const isNullItem = item => item === "" || item === undefined || item === null || (Array.isArray(item) && !item.length);
const compact = items => cc(items.map((item, index) => isNullItem(item) ? [] : [index > 0 ? "\b" : null, item]));


export const getDurationSubdivider = (term: BaseTerm): number => {
	if (term instanceof MusicEvent) {
		if (!(term instanceof Rest) || !term.isSpacer)
			return term.durationValue.subdivider;
	}
	else if (term instanceof MusicBlock)
		return lcmMulti(...term.body.map(getDurationSubdivider));
	else if (term instanceof MusicChunk)
		return lcmMulti(...term.terms.map(getDurationSubdivider));
	else if ((term instanceof Times) || (term instanceof Tuplet)) {
		const divider = term instanceof Tuplet ? term.divider : term.factor.reciprocal;
		divider.numerator *= getDurationSubdivider(term.music);

		return divider.reduced.numerator;
	}
	else if (term instanceof Repeat)
		return getDurationSubdivider(term.bodyBlock);
	else if (term instanceof Relative)
		return getDurationSubdivider(term.music);
	else if (term.isMusic)
		console.warn("[getDurationSubdivider]	unexpected music term:", term);

	return 1;
};


export const constructMusicFromMeasureLayout = (layout: measureLayout.MeasureLayout, chunks: MusicChunkMap): MusicChunk => {
	const joinMeasureSeq = (seq: measureLayout.MeasureSeq): BaseTerm[] => MusicChunk.join(seq.map(sublayout => constructMusicFromMeasureLayout(sublayout, chunks)));

	if (layout instanceof measureLayout.SingleMLayout) {
		const chunk = chunks.get(layout.measure);
		console.assert(!!chunk, "no chunk for measure:", layout.measure);

		return chunk;
	}
	else if (layout instanceof measureLayout.BlockMLayout) {
		const terms = joinMeasureSeq(layout.seq);

		return new MusicChunk(null, terms);
	}
	else if (layout instanceof measureLayout.VoltaMLayout) {
		const bodyTerms = joinMeasureSeq(layout.body);
		const alternative = layout.alternates && layout.alternates.map(alternate => new MusicBlock({body: joinMeasureSeq(alternate)}));

		const repeat = Repeat.createVolta(layout.times.toString(), new MusicBlock({body: bodyTerms}), alternative);

		return new MusicChunk(null, [repeat]);
	}
	else if (layout instanceof measureLayout.ABAMLayout) {
		const mainList = constructMusicFromMeasureLayout(layout.main, chunks);
		const main = mainList.terms.length === 1 ? mainList.terms[0] : new MusicBlock({body: mainList.terms});
		const restTerms = joinMeasureSeq(layout.rest);

		const block = new MusicBlock({body: [main, ...restTerms]});

		return new MusicChunk(null, [new Variable({name: "lotusRepeatABA"}), block]);
	}
};


export class BaseTerm {
	_location?: Location;
	_measure?: number;
	_tick?: number;
	_previous?: BaseTerm;
	_anchorPitch?: ChordElement;
	_parent?: BaseTerm;

	_headComment: Comment;
	_tailComment: Comment;

	// lotus extensional function modifier
	_functional: string;


	constructor (data: object) {
		//Object.assign(this, data);
		for (const key in data) 
			this[key] = parseRaw(data[key]);
	}


	serialize (): any[] {
		console.warn("unimplemented serilization:", this);
		return [];
	}


	join (): string {
		let words = this.serialize().filter(word => ["string", "number"].includes(typeof word)).map(word => word.toString()) as string[];
		words = words.filter((word, i) => !(i && words[i - 1] === "\n" && word === "\n"));

		let indent = 0;
		const result: string[] = [];

		const pop = char => {
			if (!char || result[result.length - 1] === char) {
				result.pop();
				return true;
			}
		};

		for (const word of words) {
			switch (word) {
			case "\b":
				// remove last space
				pop(" ");
				continue;

			case "\b\n":
				// remove last newline
				while (pop("\t")) {}
				pop("\n");
				continue;

			case "\n":
				// no space at line tail
				pop(" ");
			}

			if (/^(\}|>>)/.test(word))
				pop("\t"); // remove the last tab

			result.push(word);

			if (/\n$/.test(word)) {
				if (/(\{|<<)\n$/.test(word))
					++indent;
				else if (/^(\}|>>)/.test(word)) 
					--indent;

				if (indent)
					result.push(...Array(indent).fill("\t"));
			}
			else
				result.push(" ");
		}

		return result.join("");
	}


	relocate (source: string = this.join()) {
		const words = this.serialize()
			.filter(word => word !== null && word !== undefined
				&& (typeof word !== "string" || (/\S/.test(word) && !word.includes("\b"))))
			.map(word => typeof word === "string" ? word.replace(/\n/g, "") : word);

		const chars = source.split("");
		let line = 1;
		let column = 0;

		let wordIndex = 0;

		for (let i = 0; i < chars.length; ++i) {
			if (wordIndex >= words.length)
				break;

			const char = chars[i];

			switch (char) {
			case "\n":
				++line;
				column = 0;

				break;
			case " ":
			case "\t":
				++column;

				break;
			default:
				let word = words[wordIndex];
				while (word instanceof Locator) {
					word.set(line, column);

					++wordIndex;
					word = words[wordIndex];
				}

				if (wordIndex >= words.length)
					break;

				word = word.toString();
				if (char === word[0]) {
					i += word.length - 1;
					column += word.length;
					++wordIndex;
				}
				else {
					//debugger;
					throw new Error(`unexpected char in source: [${i}]'${char}', expect: ${word}`);
				}
			}
		}
	}


	clone (): this {
		return parseRaw(JSON.parse(JSON.stringify(this)));
	}


	get entries (): BaseTerm[] {
		return null;
	}


	get isMusic (): boolean {
		return false;
	}


	get musicChunks (): MusicChunk[] {
		if (!this.isMusic || !this.entries)
			return [];

		return [].concat(...this.entries.map(entry => entry.musicChunks));
	}


	get measures (): number[] {
		const indices = [this._measure].concat(...(this.entries || []).map(entry => entry.measures)).filter(index => Number.isInteger(index));

		return Array.from(new Set(indices));
	}


	get durationMagnitude (): number {
		return 0;
	}


	get proto () {
		return termProtoMap.get(Object.getPrototypeOf(this));
	}


	get href (): string {
		if (this._location)
			return `${this._location.lines[0]}:${this._location.columns[0]}:${this._location.columns[1]}`;

		return null;
	}


	get measureLayout (): measureLayout.MeasureLayout {
		return null;
	}


	getField (key): any {
		console.assert(!!this.entries, "[BaseTerm.getField] term's entries is null:", this);

		for (const entry of this.entries) {
			const result = entry.query(key);
			if (result)
				return result;
		}
	}


	query (key: string): any {
		void(key);
		//console.warn("term.query not implemented:", this);
	}


	appendAssignment (key, value) {
		console.assert(!!this.entries, "no entries on this term.");

		const assign = this.getField(key);
		if (assign)
			assign.value = value;
		else {
			this.entries.push(parseRaw({
				proto: "Assignment",
				key,
				value: value,
			}));
		}
	}


	findFirst (condition: Function): BaseTerm {
		if (!this.entries)
			return null;

		if (BaseTerm.isPrototypeOf(condition)) {
			const termClass = condition;
			condition = term => term instanceof termClass;
		}
	
		for (const entry of this.entries) {
			if (condition(entry))
				return entry;
	
			if (entry instanceof BaseTerm) {
				const result = entry.findFirst(condition);
				if (result)
					return result;
			}
		}
	}


	findLast (condition: any): BaseTerm {
		if (!this.entries)
			return null;

		if (BaseTerm.isPrototypeOf(condition)) {
			const termClass = condition;
			condition = term => term instanceof termClass;
		}
	
		const reversedEntries = [...this.entries];
		reversedEntries.reverse();

		for (const entry of reversedEntries) {
			if (condition(entry))
				return entry;
	
			if (entry instanceof BaseTerm) {
				const result = entry.findLast(condition);
				if (result)
					return result;
			}
		}
	}


	findAll (condition: any): any[] {
		if (!this.entries)
			return [];

		if (BaseTerm.isPrototypeOf(condition)) {
			const termClass = condition;
			condition = term => term instanceof termClass;
		}

		const result = [];

		for (const entry of this.entries) {
			if (condition(entry))
				result.push(entry);
	
			if (entry instanceof BaseTerm)
				result.push(...entry.findAll(condition));
		}

		return result;
	}


	forEachTerm (termClass, handle) {
		if (!this.entries)
			return;

		for (const entry of this.entries) {
			if (entry instanceof termClass)
				handle(entry);

			if (entry instanceof BaseTerm)
				entry.forEachTerm(termClass, handle);
		}
	}


	forEachTopTerm (termClass, handle) {
		if (!this.entries)
			return;

		for (const entry of this.entries) {
			if (entry instanceof termClass)
				handle(entry);
			else if (entry instanceof BaseTerm)
				entry.forEachTopTerm(termClass, handle);
		}
	}


	toJSON () {
		// exlude meta fields in JSON
		const fields = Object.keys(this).filter(key => !/^_/.test(key));
		const data = pick(this, fields);

		Object.entries(data).forEach(([key, value]) => {
			if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof BaseTerm))
				data[key] = {proto: "_PLAIN", ...value};
		});

		return {
			proto: this.proto,
			...data,
		};
	}


	static isTerm (x): boolean {
		return typeof x === "object" && x instanceof BaseTerm;
	}


	static optionalSerialize (item: any): any[] {
		//return BaseTerm.isTerm(item) ? (item as BaseTerm).serialize() : (item === undefined ? [] : [item]);
		if (!BaseTerm.isTerm(item))
			return item === undefined ? [] : [item];

		return [
			...BaseTerm.optionalSerialize(item._headComment),
			...item.serialize(),
			...(item._tailComment ? ["\b\n", "\t"] : []),
			...BaseTerm.optionalSerialize(item._tailComment),
		];
	}


	static serializeScheme (item: any): any[] {
		if (typeof item === "boolean")
			item = item ? "#t" : "#f";

		return BaseTerm.optionalSerialize(item);
	}
}


export class Root extends BaseTerm {
	sections: BaseTerm[];


	serialize () {
		return cc(this.sections.map(section => [...BaseTerm.optionalSerialize(section), "\n\n"]));
	}


	get entries (): BaseTerm[] {
		return this.sections;
	}


	getBlock (head): Block {
		return this.entries.find((entry: any) => entry.head === head || (entry.head === "\\" + head)) as Block;
	}


	get includeFiles (): string[] {
		return this.sections.filter(section => section instanceof Include).map((include: Include) => include.filename);
	}


	static priorityForSection (term: BaseTerm): number {
		if (term instanceof Version)
			return 0;

		if (term instanceof Language)
			return 1;

		if (term instanceof Scheme)
			return 3;

		if (term instanceof Assignment)
			return 7;

		if (term instanceof Block) {
			switch (term.head) {
			case "\\header":
				return 2;

			case "\\paper":
				return 4;

			case "\\layout":
				return 5;

			case "\\score":
				return 10;
			}
		}

		return Infinity;
	}


	reorderSections () {
		this.sections.sort((s1, s2) => Root.priorityForSection(s1) - Root.priorityForSection(s2));
	}
};


export class Primitive extends BaseTerm {
	exp: string | number;


	serialize () {
		return [this.exp];
	}
};


export class LiteralString extends BaseTerm {
	exp: string


	static fromString (content: string): LiteralString {
		return new LiteralString({exp: JSON.stringify(content)});
	}


	serialize () {
		return [this.exp];
	}


	toString () {
		try {
			return eval(this.exp);
		}
		catch (err) {
			console.warn("invalid lilypond string exp:", this.exp);
			return this.exp;
		}
	}
};


export class Command extends BaseTerm {
	cmd: string;
	args: any[];


	static createSet (key: string|BaseTerm, value: BaseTerm): Command {
		return new Command({cmd: "set", args: [new Assignment({key, value})]});
	}


	constructor (data) {
		super(data);

		this.args.forEach(term => {
			if (term instanceof MusicBlock || term instanceof Block)
				term._parent = this;
		});
	}


	serialize () {
		return [
			"\\" + this.cmd,
			...[].concat(...this.args.map(BaseTerm.optionalSerialize)),
			["break", "pageBreak", "overrideProperty"].includes(this.cmd) ? "\n" : null,
		];
	}


	get entries () {
		return this.args.filter(arg => arg instanceof BaseTerm);
	}


	get isMusic (): boolean {
		return this.args.some(arg => arg.isMusic);
	}


	get musicChunks (): MusicChunk[] {
		if (this.cmd === "alternative")
			return [].concat(...this.args[0].body.map(term => term.musicChunks));

		return [].concat(...this.entries.map(entry => entry.musicChunks));
	}


	get isRepeatWithAlternative () {
		return this.cmd === "repeat"
			&& this.args[2] instanceof MusicBlock
			&& this.args[3]
			&& this.args[3].cmd === "alternative";
	}


	get durationMagnitude (): number {
		switch (this.cmd) {
		// TODO: refine this in Times
		case "times": {
			const factor = eval(this.args[0]);
			return this.args[1].durationMagnitude * factor;
		}

		// TODO: refine this in Tuplet
		case "tuplet": {
			const factor = 1 / eval(this.args[0]);
			return this.args[this.args.length - 1].durationMagnitude * factor;
		}

		case "afterGrace":
			return this.args[0].durationMagnitude;

		default:
			if (this instanceof Grace)
				return 0;

			return this.args.filter(arg => arg instanceof BaseTerm).reduce((magnitude, term) => magnitude + term.durationMagnitude, 0);
		}
	}


	get measureLayout (): measureLayout.MeasureLayout {
		const args = [...this.args].reverse();
		for (const arg of args) {
			const layout = arg instanceof BaseTerm && arg.measureLayout;
			if (layout)
				return layout;
		}

		return null;
	}


	getAssignmentPair (): {key: any, value: any} {
		if (this.args[0] instanceof Assignment)
			return {key: this.args[0].key, value: this.args[0].value};

		if (this.args[1] instanceof Assignment)
			return {key: this.args[0], value: this.args[1].value};

		if (typeof this.args[0] === "string")
			return {key: this.args[0], value: ""};

		return null;
	}
};


export class Variable extends Command {
	name: string


	constructor ({name}) {
		super({cmd: name, args: []});

		this.name = name;
	}


	toJSON (): any {
		return {
			proto: this.proto,
			name: this.name,
		};
	}


	queryValue (dict: BaseTerm): any {
		const field = dict.getField(this.name);

		return field && field.value;
	}


	get isMusic (): boolean {
		if ([MAIN_SCORE_NAME].includes(this.name))
			return true;

		return false;
	}
};


export class MarkupCommand extends Command {
	toString () {
		const strs = [];
		this.forEachTerm(LiteralString, term => strs.push(term.toString()));

		return strs.join("\n");
	}
};


export class Repeat extends Command {
	static createVolta (times: string, body: MusicBlock, alternative?: MusicBlock[]): Repeat {
		const args: any[] = [
			"volta",
			times,
			body,
		];

		if (alternative) {
			args.push(new Command({
				cmd: "alternative",
				args: [new MusicBlock({body: alternative})],
			}));
		}

		return new Repeat({cmd: "repeat", args});
	}


	get type (): string {
		return this.args[0];
	}


	get times () {
		return Number(this.args[1]);
	}


	get bodyBlock (): MusicBlock {
		return this.args[2];
	}


	get alternativeBlocks (): MusicBlock[] {
		return this.args[3] && this.args[3].args[0].body;
	}


	// this result length equal to times, if not null
	get completeAlternativeBlocks (): MusicBlock[] {
		if (!this.alternativeBlocks || !this.alternativeBlocks.length)
			return null;

		if (this.alternativeBlocks.length >= this.times)
			return this.alternativeBlocks.slice(0, this.times);

		const list = [];
		for (let i = 0; i < this.times - this.alternativeBlocks.length; ++ i)
			list.push(this.alternativeBlocks[0]);
		list.push(...this.alternativeBlocks);

		return list;
	}


	get measureLayout (): measureLayout.MeasureLayout {
		switch (this.type) {
		case "volta": {
			const layout = new measureLayout.VoltaMLayout();
			layout.times = this.times;
			layout.body = this.bodyBlock.measureLayout.seq;
			layout.alternates = this.alternativeBlocks && this.alternativeBlocks.map(block => block.measureLayout.seq);

			return layout;
		}

		case "tremolo":
			return this.bodyBlock.measureLayout;

		default:
			console.warn("unsupported repeat type:", this.type);
		}

		return null;
	}


	// for tremolo
	get sumDuration (): Duration {
		if (this.bodyBlock instanceof MusicEvent)
			return Duration.fromMagnitude(this.args[2].durationMagnitude * this.times);
		else if (this.bodyBlock instanceof MusicBlock) {
			const events = this.bodyBlock.body.filter(term => term instanceof MusicEvent);
			const magnitude = events.reduce((m, event) => m + event.durationMagnitude, 0) * this.times;

			return Duration.fromMagnitude(magnitude);
		}

		return null;
	}


	get singleTremolo (): boolean {
		if (this.type === "tremolo") {
			if (this.bodyBlock instanceof MusicEvent)
				return true;

			if (this.bodyBlock instanceof MusicBlock) {
				const events = this.bodyBlock.body.filter(term => term instanceof MusicEvent);
				return events.length === 1;
			}
		}

		return false;
	}


	// \repeat {body} \alternative {{alter1} {alter2}}		=> body alter1 body alter2
	getUnfoldTerms (): BaseTerm[] {
		const completeAlternativeBlocks = this.completeAlternativeBlocks;

		const list = [];
		for (let i = 0; i < this.times; ++i) {
			list.push(...this.bodyBlock.clone().body);

			if (completeAlternativeBlocks)
				list.push(...completeAlternativeBlocks[i].clone().body);
		}

		return list;
	}


	// \repeat {body} \alternative {{alter1} {alter2}}		=> body alter1 alter2
	getPlainTerms (): BaseTerm[] {
		const list = [...this.bodyBlock.clone().body];

		const alternativeBlocks = this.alternativeBlocks;
		if (alternativeBlocks)
			alternativeBlocks.forEach(block => list.push(...block.clone().body));

		return list;
	}


	// \repeat {body} \alternative {{alter1} {alter2}}		=> body alter2
	getTailPassTerms (): BaseTerm[] {
		const list = [...this.bodyBlock.clone().body];

		const alternativeBlocks = this.alternativeBlocks;
		if (alternativeBlocks)
			list.push(...alternativeBlocks[alternativeBlocks.length - 1].clone().body);

		return list;
	}
};


export class Relative extends Command {
	static makeBlock (block: MusicBlock, {anchor}: {anchor?: ChordElement} = {}): Relative {
		if (!anchor) {
			const chord = block.findFirst(Chord) as Chord;
			anchor = chord && chord.anchorPitch;
		}

		return new Relative({cmd: "relative", args: [anchor, block].filter(term => term)});
	}


	get anchor (): ChordElement {
		if (this.args[0] instanceof ChordElement)
			return this.args[0];

		return null;
	}


	get music (): BaseTerm {
		return this.args[this.args.length - 1];
	}


	get headChord (): Chord {
		return this.findFirst(Chord) as Chord;
	}


	get tailPitch (): ChordElement {
		const tail = this.findLast(Chord) as Chord;

		return tail && tail.absolutePitch;
	}


	// with side effect
	shiftBody (newAnchor?: ChordElement): BaseTerm[] {
		const headChord = this.headChord;
		if (newAnchor && headChord) {
			headChord.shiftAnchor(newAnchor);
			headChord._anchorPitch = null;
			//console.log("shiftAnchor.post:", headChord.join(), headChord);
		}

		const music = this.music;
		if (music instanceof MusicBlock) {
			//music.clearPitchCache();
			return music.body;
		}

		return [music];
	}
}


export class ParallelMusic extends Command {
	get varNames (): string[] {
		return ((this.args[0].exp as SchemePointer).value as SchemeFunction).asList as string[];
	}


	get body (): MusicBlock {
		return this.args[1];
	}


	get voices (): MusicVoice[] {
		const voiceNames = this.varNames;
		const chunks = this.body.musicChunks;
		const measureCount = Math.ceil(chunks.length / voiceNames.length);

		return voiceNames.map((name, index) => ({
			name: name.toString(),
			body: Array(measureCount).fill(null).map((_, m) => chunks[m * voiceNames.length + index]).filter(Boolean),
		}));
	}
};


export class TimeSignature extends Command {
	get value (): FractionNumber {
		return FractionNumber.fromExpression(this.args[0]);
	}
};


export class Partial extends Command {
	get duration (): Duration {
		return this.args[0];
	}
};


export class Times extends Command {
	get factor (): FractionNumber {
		return FractionNumber.fromExpression(this.args[0]);
	}


	get music (): BaseTerm {
		return this.args[this.args.length - 1];
	}
};


export class Tuplet extends Command {
	get divider (): FractionNumber {
		return FractionNumber.fromExpression(this.args[0]);
	}


	get music (): BaseTerm {
		return this.args[this.args.length - 1];
	}
};


export class Grace extends Command {
	get music (): BaseTerm {
		return this.args[this.args.length - 1];
	}
};


export class AfterGrace extends Command {
	get body (): BaseTerm {
		return this.args[0];
	}

	get grace (): BaseTerm {
		return this.args[1];
	}


	get measureLayout (): measureLayout.MeasureLayout {
		return measureLayout.BlockMLayout.fromSeq([
			this.body.measureLayout,
			this.grace.measureLayout,
		]);
	}
};


export class Clef extends Command {
	get clefName (): string {
		return this.args[0].toString();
	}
};


export class KeySignature extends Command {
	get keyPitch (): ChordElement {
		return new ChordElement({pitch: this.args[0], options: {proto: "_PLAIN"}});
	}


	get key (): number {
		const keyPitch = this.keyPitch;
		const minor = this.args[1] === "\\minor";
		const phonetOrder = idioms.FIFTH_PHONETS.indexOf(keyPitch.phonet);

		return phonetOrder + (minor ? -4 : -1) + keyPitch.alterValue * 7;
	}
};


export class OctaveShift extends Command {
	get value (): number {
		return this.args[0].exp;
	}
};


export class Include extends Command {
	static create (filename: string): Include {
		return new Include({cmd: "include", args: [LiteralString.fromString(filename)]});
	}


	get filename (): string {
		return this.args[0].toString();
	}
};


export class Version extends Command {
	static get default (): Version {
		return new Version({cmd: "version", args: [LiteralString.fromString(LILYPOND_VERSION)]});
	}


	get version (): string {
		return this.args[0].toString();
	}
};


export class Language extends Command {
	static make (language: string): Language {
		return new Language({cmd: "language", args: [LiteralString.fromString(language)]});
	}


	get language (): string {
		return this.args[0].toString();
	}
};


export class LyricMode extends Command {
	get block (): MusicBlock {
		return this.args[0];
	}
};


export class ChordMode extends Command {
	get block (): MusicBlock {
		return this.args[0];
	}
};


export class Transposition extends Command {
	get transposition (): number {
		return this.args[0].pitchValue - 60;
	}
};


export class StemDirection extends Command {
	get direction (): string {
		return this.cmd.substr(4);
	}
};


export class Change extends Command {
	get key (): string {
		return this.args[0].toString();
	}


	get value (): string {
		return this.args[1].toString();
	}
};


export class Block extends BaseTerm {
	block: string;
	head: (string|string[]);
	body: BaseTerm[];


	constructor (data) {
		super(data);

		this.body = this.body.map(parseRawEnforce);
	}


	serialize () {
		const heads = Array.isArray(this.head) ? this.head : (this.head ? [this.head] : []);

		return [
			...heads,
			"{\n",
			...cc(this.body.map(section => [...BaseTerm.optionalSerialize(section), "\n"])),
			"}\n",
		];
	}


	get entries () {
		return this.body;
	}


	get isMIDIDedicated () {
		const subBlocks = this.body.filter(term => term instanceof Block) as Block[];

		return subBlocks.some(term => term.head === "\\midi")
			&& !subBlocks.some(term => term.head === "\\layout");
	}


	get assignmentDict (): {[key: string]: string} {
		const assignments = this.body.filter(term => term instanceof Assignment) as Assignment[];

		return assignments.reduce((dict, assignment) => ((dict[assignment.key.toString()] = assignment.value.toString()), dict), {});
	}
};


export class InlineBlock extends Block {
	serialize () {
		return [
			"{",
			...cc(this.body.map(BaseTerm.optionalSerialize)),
			"}",
		];
	}
};


export class MusicBlock extends BaseTerm {
	body: BaseTerm[];


	static fromTerms (terms: BaseTerm[]): MusicBlock {
		const block = new MusicBlock({body: [...terms]});
		block.clarifyHead();

		return block;
	}


	constructor (data) {
		super(data);

		this.body = this.body.map(parseRawEnforce);
	}


	serialize () {
		return [
			"{\n",
			...cc(this.body.map(BaseTerm.optionalSerialize)),
			"\n",
			"}\n",
		];
	}


	clone (): this {
		if (this._parent) {
			const parent = this._parent.clone();
			const block = parent.findFirst(MusicBlock);
			console.assert(block && block._parent === parent, "invalid block-parent relation", parent, block);

			return block as this;
		}

		return BaseTerm.prototype.clone.call(this) as this;
	}


	get entries () {
		return this.body;
	}


	get isMusic (): boolean {
		return true;
	}


	get musicChunks (): MusicChunk[] {
		const chunks = [];
		let currentChunk = new MusicChunk(this);

		const dumpChunk = () => {
			if (currentChunk.size)
				chunks.push(currentChunk);

			currentChunk = new MusicChunk(this);
		};

		for (const term of this.entries) {
			if (term instanceof Repeat) {
				dumpChunk();
				chunks.push(...term.musicChunks);
			}
			else if (term instanceof Divide)
				dumpChunk();
			else
				currentChunk.push(term);
		}

		dumpChunk();

		return chunks;
	}


	// [deprecated]
	// for parallelMusic only
	get voiceNames () {
		const header = this._parent as Command;
		if (header && header.cmd === "parallelMusic") {
			if (header.args[0] instanceof Scheme && header.args[0].exp instanceof SchemePointer && header.args[0].exp.value instanceof SchemeFunction) {
				const voices = header.args[0].exp.value.asList;
				return voices;
			}
		}

		return null;
	}


	// [deprecated]
	get voices (): MusicVoice[] {
		const voiceNames = this.voiceNames;
		if (!voiceNames)
			return [{body: this.musicChunks}];

		const chunks = this.musicChunks;
		const measureCount = Math.ceil(chunks.length / voiceNames.length);

		return voiceNames.map((name, index) => ({
			name: name.toString(),
			body: Array(measureCount).fill(null).map((_, m) => chunks[m * voiceNames.length + index]).filter(chunk => chunk),
		}));
	}


	get durationMagnitude (): number {
		return this.body.reduce((magnitude, term) => magnitude + term.durationMagnitude, 0);
	}


	get isRelative (): boolean {
		return this._parent instanceof Relative;
	}


	get anchorPitch (): ChordElement {
		if (this.isRelative) 
			return (this._parent as Relative).anchor;

		return null;
	}


	get measures (): number[] {
		// make a continouse indices list
		const subterms = this.findAll(term => term.isMusic);
		const subIndices = [].concat(...subterms.map(term => term.measures)).filter(index => Number.isInteger(index));
		if (!subIndices.length)
			return [];

		const min = Math.min(...subIndices);
		const max = Math.max(...subIndices);

		return Array(max + 1 - min).fill(null).map((_, i) => i + min);
	}


	get notes (): Chord[] {
		const notes = this.body.filter(term => term instanceof Chord && !term.isRest) as Chord[];
		this.forEachTopTerm(MusicBlock, block => notes.push(...block.notes));

		return notes;
	}


	get sonicNotes (): Chord[] {
		return this.notes.filter(note => !note.completeTied);
	}


	get noteTicks (): number[] {
		const ticks = this.sonicNotes.map(note => note._tick);
		return Array.from(new Set(ticks)).sort((t1, t2) => t1 - t2);
	}


	get measureTicks (): [number, number][] {
		const tickTable: {[key: string]: number} = {};

		this.body.forEach(term => {
			if (Number.isFinite(term._measure) && Number.isFinite(term._tick)) {
				if (!Number.isFinite(tickTable[term._measure]))
					tickTable[term._measure] = term._tick;
			}
		});

		return Object.entries(tickTable).map(([measure, tick]) => [Number(measure), tick]);
	}


	get measureLayout (): measureLayout.MeasureLayout {
		const seq = this.body.filter(term => term.isMusic).map(term => term.measureLayout).filter(Boolean);

		if (this._functional === "lotusRepeatABA") {
			const [main, ...rest] = seq;

			const layout = new measureLayout.ABAMLayout();
			layout.main = main;
			layout.rest = measureLayout.BlockMLayout.trimSeq(rest);

			return layout;
		}

		return measureLayout.BlockMLayout.fromSeq(seq);
	}


	get measureChunkMap (): MusicChunkMap {
		const map = new Map<number, MusicChunk>();
		this.body.forEach(term => {
			if (Number.isInteger(term._measure) && !(term instanceof Divide)) {
				if (!map.get(term._measure))
					map.set(term._measure, new MusicChunk(this));

				const chunk = map.get(term._measure);
				chunk.terms.push(term);
			}
		});

		return map;
	}


	clearPitchCache () {
		this.forEachTerm(ChordElement, pitch => {
			pitch._absolutePitch = null;
			//pitch._previous = null;
		});
	}


	updateChordAnchors () {
		const chord = this.findFirst(Chord) as Chord;
		if (chord)
			chord._anchorPitch = chord._anchorPitch || this.anchorPitch;

		this.clearPitchCache();
	}


	// deprecated
	updateChordChains () {
		let previous: MusicEvent = null;

		this.updateChordAnchors();

		this.forEachTerm(MusicBlock, block => block.updateChordAnchors());

		this.forEachTerm(MusicEvent, event => {
			event._previous = previous;

			previous = event;
		});
	}


	// with side effect
	spreadRepeatBlocks ({ignoreRepeat = true, keepTailPass = false} = {}): this {
		this.forEachTerm(MusicBlock, block => block.spreadRepeatBlocks());

		this.body = cc(this.body.map(term => {
			if (term instanceof Repeat) {
				if (!ignoreRepeat)
					return term.getUnfoldTerms();
				else if (keepTailPass)
					return term.getTailPassTerms();
				else
					return term.getPlainTerms();
			}
			else
				return [term];
		}));

		return this;
	}


	/*// with side effect
	spreadRelativeBlocks (): this {
		this.forEachTerm(MusicBlock, block => block.spreadRelativeBlocks());

		let anchorPitch = null;

		this.body = cc(this.body.map(term => {
			if (term instanceof Relative) {
				const list = term.shiftBody(anchorPitch);

				anchorPitch = term.tailPitch || anchorPitch;

				return list;
			}
			else
				return [term];
		}));

		return this;
	}*/


	// with side effect
	unfoldDurationMultipliers (): this {
		let timeDenominator = 4;

		const unfoldMultipliers = (term): BaseTerm[] => {
			if (term instanceof TimeSignature)
				timeDenominator = term.value.denominator;

			if (!(term instanceof MusicEvent) || !term.duration || !term.duration.multipliers || !term.duration.multipliers.length)
				return [term];

			const factor = term.duration.multipliers.reduce((factor, multiplier) => factor * Number(multiplier), 1);
			if (!Number.isInteger(factor) || factor <= 0)
				return [term];

			const denominator = Math.max(term.duration.denominator, timeDenominator);

			const event = term.clone() as MusicEvent;
			event.duration.multipliers = [];

			// break duration into multiple rest events
			const restCount = (event.duration.magnitude / WHOLE_DURATION_MAGNITUDE) * (factor - 1) * denominator;
			if (!Number.isInteger(restCount))
				console.warn("Rest count is not integear:", restCount, denominator, event.duration.magnitude, factor);

			const rests = Array(Math.floor(restCount)).fill(null).map(() => 
				new Rest({name: "s", duration: new Duration({number: denominator, dots: 0})}));

			return [event, ...rests];
		};

		this.body = cc(this.body.map(unfoldMultipliers));

		return this;
	}


	/*// pure
	flatten ({spreadRepeats = false} = {}): Relative {
		this.updateChordChains();

		const chord = this.findFirst(Chord) as Chord;
		const anchor = this.anchorPitch || (chord && chord.anchorPitch);

		const block = this.clone();
		if (spreadRepeats)
			block.spreadRepeatBlocks();
		block.spreadRelativeBlocks();
		block.unfoldDurationMultipliers();

		return Relative.makeBlock(block, {anchor: anchor && anchor.clone()});
	}*/


	// with side effect
	expandVariables (dict: BaseTerm): this {
		this.body = this.body.map(term => {
			if (term instanceof Variable) {
				const value = term.queryValue(dict);
				const clonedValue = value instanceof BaseTerm ? value.clone() : value;

				if (clonedValue instanceof BaseTerm) {
					clonedValue.forEachTerm(MusicBlock, block => block.expandVariables(dict));

					if (clonedValue instanceof MusicBlock)
						clonedValue.expandVariables(dict);
				}

				return clonedValue;
			}

			return term;
		});

		return this;
	}


	// with side effects
	redivide ({recursive = true, measureHeads = null}: {recursive?: boolean, measureHeads?: number[]} = {}) {
		if (recursive) {
			this.forEachTerm(MusicBlock, block => {
				if (!block._parent || block._parent.cmd !== "alternative")
					block.redivide({recursive, measureHeads});
			});
		}

		// split rests
		if (measureHeads) {
			this.body = [].concat(...this.body.map(term => {
				if (!(term instanceof Rest) || term.name !== "s" || !Number.isInteger(term._measure))
					return [term];

				const nextHead = measureHeads[term._measure];
				const endTick = term._tick + term.durationMagnitude;
				if (nextHead > 0 && endTick > nextHead) {
					const post_events = term.post_events;

					let startTick = term._tick;
					const rests = [];
					let nextMeasure;
					for (nextMeasure = term._measure; nextMeasure < measureHeads.length && endTick > measureHeads[nextMeasure]; ++nextMeasure) {
						const duration = Duration.fromMagnitude(measureHeads[nextMeasure] - startTick);
						if (!duration) {
							console.warn("invalid middle rest duration, splitting gave up:", measureHeads[nextMeasure] - startTick, term);
							return [term];
						}
	
						const rest = new Rest({name: "s", duration, post_events: []});
						rest._measure = nextMeasure;
						rest._lastMeasure = nextMeasure;
						rests.push(rest);

						console.assert(!!rest.duration, "middle splitted rest duration invalid:", measureHeads[nextMeasure] - startTick);

						startTick = measureHeads[nextMeasure];
					}

					const duration = Duration.fromMagnitude(endTick - startTick);
					if (!duration) {
						console.warn("invalid tail rest duration, splitting gave up:", endTick - startTick, term);
						return [term];
					}

					const rest = new Rest({name: "s", duration, post_events: post_events && [...post_events]});
					rest._measure = nextMeasure;
					rest._lastMeasure = nextMeasure;
					rests.push(rest);

					console.assert(rests.reduce((sum, rest) => sum + rest.durationMagnitude, 0) === term.durationMagnitude, "duration splitting error:", rests, term);
					//if (rests.reduce((sum, rest) => sum + rest.durationMagnitude, 0) !== term.durationMagnitude)
					//	debugger;

					return rests;
				}

				return [term];
			}));
		}

		const isPostTerm = term => !term
			|| term instanceof PostEvent
			|| (term as Primitive).exp === "~"
			|| ["bar", "arpeggio", "glissando", "sustainOff", "sustainOn"].includes((term as Command).cmd)
			;

		const list = this.body.filter(term => !(term instanceof Divide));
		let measure = null;
		for (const term of list) {
			if (Number.isInteger(measure) && isPostTerm(term))
				term._measure = measure;
			else
				measure = term._measure;
		}

		const body: BaseTerm[] = [];
		const measures = new Set();

		list.reverse().forEach(term => {
			if (term instanceof BaseTerm) {
				const newMeasures = term.measures.filter(m => !measures.has(m));
				if (newMeasures.length) {
					const comment = " " + newMeasures[0] + (newMeasures.length > 1 ? "-" + Math.max(...newMeasures) : "");

					if (body.length)
						body.push(new Divide({_tailComment: Comment.createSingle(comment)}));

					newMeasures.forEach(m => measures.add(m));
				}
			}

			body.push(term);
		});

		this.body = body.reverse();
	}


	clarifyHead () {
		const terms = this.body;

		const head = terms.find(term => term.isMusic);
		if (head instanceof MusicEvent) {
			// clarify the first music event content
			const firstEventIndex = terms.indexOf(head);
			if (firstEventIndex >= 0) {
				const firstEvent = terms[firstEventIndex] as MusicEvent;
				//console.log("firstEvent:", firstEvent);
				if (firstEvent._previous) {
					const clarified = firstEvent.clarified;
	
					terms.splice(firstEventIndex, 1, clarified);
					//console.log("terms:", firstEventIndex, terms, clarified);
				}
			}
		}
		else if (head) {
			const block = head.findFirst(MusicBlock) as MusicBlock;
			if (block)
				block.clarifyHead();
			else
				console.warn("[MusicBlock.clarifyHead] unexpected music head:", head);
		}
	}


	absoluteToRelative (): Relative {
		const anchor = this.findFirst(Chord) as Chord;
		if (!anchor)
			return null;

		const anchorPitch = anchor.absolutePitch;
		let pitch = anchorPitch;

		const newBody = this.clone();
		newBody.forEachTerm(Chord, chord => {
			const newPitch = chord.absolutePitch;
			chord.makeRelativeTo(pitch);

			pitch = newPitch;
		});

		return Relative.makeBlock(newBody, {anchor: anchorPitch});
	}
};


export class SimultaneousList extends BaseTerm {
	list: BaseTerm[];


	serialize () {
		return [
			"<<\n",
			...cc(this.list.map(item => [...BaseTerm.optionalSerialize(item), "\n"])),
			">>\n",
		];
	}


	removeStaffGroup () {
		for (let i = 0; i < this.list.length; ++i) {
			const item: any = this.list[i];
			if (item.head instanceof Command && item.head.args && item.head.args[0] === "StaffGroup")
				this.list[i] = item.body;
		}

		this.list.forEach(item => {
			if (item instanceof SimultaneousList)
				item.removeStaffGroup();
		});
	}


	get isMusic (): boolean {
		return true;
	}


	get entries () {
		return this.list;
	}


	get durationMagnitude (): number {
		return Math.max(...this.list.filter(term => term instanceof BaseTerm).map(term => term.durationMagnitude));
	}


	get measureLayout (): measureLayout.MeasureLayout {
		const track = this.list.find(term => term instanceof BaseTerm && term.measureLayout);
		return track && track.measureLayout;
	}
};


export class ContextedMusic extends BaseTerm {
	head: Command;
	body: BaseTerm;
	lyrics?: BaseTerm;


	serialize () {
		return [
			...BaseTerm.optionalSerialize(this.head),
			...BaseTerm.optionalSerialize(this.body),
			...BaseTerm.optionalSerialize(this.lyrics),
		];
	}


	get isMusic (): boolean {
		return true;
	}


	get entries () {
		return [this.head, this.body];
	}


	get type (): string {
		return this.head.args[0];
	}


	get durationMagnitude (): number {
		return this.body.durationMagnitude;
	}


	get withClause (): Command {
		if (this.head.args[2] && this.head.args[2] instanceof Command && this.head.args[2].cmd === "with")
			return this.head.args[2];
	}


	get contextDict (): {[key: string]: string} {
		const withEntries = this.withClause ? Object.entries((this.withClause.args[0] as Block).assignmentDict) : [];
		const entries = withEntries.map(([key, value]) => [`${this.type}.${key}`, value]);

		const pair = this.head.getAssignmentPair();
		if (pair)
			entries.push([pair.key.toString(), pair.value.toString()]);

		return entries.reduce((dict, [key, value]) => ((dict[key] = value), dict), {});
	}


	get list (): BaseTerm[] {
		if (this.body instanceof SimultaneousList)
			return this.body.list;

		return null;
	}


	set list (value: BaseTerm[]) {
		if (this.body instanceof SimultaneousList)
			this.body.list = value;
	}


	get measureLayout (): measureLayout.MeasureLayout {
		return this.body.measureLayout;
	}
};


export class Divide extends BaseTerm {
	serialize () {
		return ["|", "\n"];
	}
}


export class Scheme extends BaseTerm {
	exp: (boolean|BaseTerm);


	serialize () {
		if (BaseTerm.isTerm(this.exp))
			return ["#", "\b", ...(this.exp as BaseTerm).serialize()];
		else if (typeof this.exp === "boolean")
			return ["#", "\b", this.exp ? "#t" : "#f"];
		// TODO: enhance grammar to parse empty scheme list
		//else if (this.exp === null)
		//	return ["#", "\b", "'()"];
		else
			return ["#", "\b", this.exp];
	}


	query (key: string): any {
		if (this.exp instanceof SchemeFunction)
			return this.exp.query(key);
	}


	get entries () {
		if (this.exp instanceof BaseTerm)
			return [this.exp];

		return [];
	}
};


export class SchemeFunction extends BaseTerm {
	func: (string | BaseTerm);
	args: (boolean | string | BaseTerm)[];


	serialize () {
		return [
			"(", "\b",
			...BaseTerm.optionalSerialize(this.func),
			...cc(this.args.map(BaseTerm.serializeScheme)),
			"\b", ")",
		];
	}


	query (key: string): any {
		if (key === this.func) {
			const term = this;

			return {
				get value () {
					return term.args.length === 1 ? term.args[0] : term.args;
				},

				set value (value) {
					if (term.args.length === 1)
						term.args[0] = value as string|BaseTerm;
					else
						term.args = value as (string|BaseTerm)[];
				},
			};
		}
	}


	get asList (): (boolean | string | BaseTerm)[] {
		return [this.func, ...this.args];
	}


	get entries () {
		return this.asList.filter(term => term instanceof BaseTerm) as BaseTerm[];
	}
};


export class SchemePair extends BaseTerm {
	left: any;
	right: any;


	serialize () {
		return [
			"(", "\b",
			...BaseTerm.optionalSerialize(this.left), ".", ...BaseTerm.optionalSerialize(this.right),
			"\b", ")",
		];
	}
};


export class SchemePointer extends BaseTerm {
	value: any;


	serialize () {
		const content = this.value === null ? ["()"] : BaseTerm.optionalSerialize(this.value);

		return [
			"'", "\b", ...content,
		];
	}


	get entries () {
		if (this.value instanceof BaseTerm)
			return [this.value];

		return [];
	}
};


export class SchemeEmbed extends BaseTerm {
	value: Root;


	serialize () {
		return [
			"#{",
			...BaseTerm.optionalSerialize(this.value),
			"#}",
		];
	}
};


export class Assignment extends BaseTerm {
	key: (string|any[]);
	value: any;


	constructor (data) {
		super(data);

		if (this.value instanceof BaseTerm)
			this.value._parent = this;
	}


	serialize () {
		const keys = (Array.isArray(this.key) ? this.key : [this.key]).map(BaseTerm.optionalSerialize);
		const values = (Array.isArray(this.value) ? this.value : [this.value]).map(BaseTerm.optionalSerialize);

		return [
			...cc(keys),
			"=",
			...cc(values),
		];
	}


	get entries () {
		if (this.value instanceof BaseTerm)
			return [this.value];

		return null;
	}


	query (key) {
		if (this.key === key) {
			const term = this;

			return {
				get value () {
					return term.value;
				},

				set value (value) {
					term.value = value;
				},
			};
		}
	}
};


export class MusicEvent extends BaseTerm {
	duration?: Duration;
	post_events?: (string | PostEvent)[];

	declare _previous?: MusicEvent;
	//_anchorPitch?: ChordElement;
	_lastMeasure?: number;


	constructor (data: object) {
		super(data);

		if (this.post_events)
			this.post_events = this.post_events.map(parseRaw);
	}


	getPreviousT (T) {
		if (this._previous instanceof T)
			return this._previous;

		if (this._previous)
			return this._previous.getPreviousT(T);
	}


	get durationValue (): Duration {
		return this.duration || (this._previous ? this._previous.durationValue : Duration.default);
	}


	get durationMagnitude (): number {
		return this.durationValue.magnitude;
	}


	get division (): number {
		return this.durationValue.division;
	}


	get withMultiplier () {
		return this.duration && this.duration.withMultiplier;
	}


	get isMusic (): boolean {
		return true;
	}


	get isTying (): boolean {
		return this.post_events && this.post_events.some(event => event instanceof PostEvent && event.isTying);
	}


	get isStaccato (): boolean {
		return this.post_events && this.post_events.some(event => event instanceof PostEvent && event.isStaccato);
	}


	// to be implement in derived classes
	get isRest (): boolean {
		return null;
	}


	get beamOn (): boolean {
		return this.post_events && this.post_events.includes("[");
	}


	get beamOff (): boolean {
		return this.post_events && this.post_events.includes("]");
	}


	get measures (): number[] {
		if (!Number.isFinite(this._measure) || !Number.isFinite(this._lastMeasure))
			return [];

		return Array(this._lastMeasure + 1 - this._measure).fill(null).map((_, i) => this._measure + i);
	}


	get measureLayout (): measureLayout.MeasureLayout {
		if (this.measures.length > 1)
			return measureLayout.BlockMLayout.fromSeq(this.measures.map(measure => measureLayout.SingleMLayout.from(measure)));

		if (this.measures.length === 1)
			return measureLayout.SingleMLayout.from(this._measure);

		return null;
	}


	get implicitType (): ImplicitType {
		if (this.post_events) {
			for (const event of this.post_events) {
				if (event instanceof PostEvent && event.arg instanceof Command) {
					switch (event.arg.cmd) {
					case "startTrillSpan":
					case "trill":
						return ImplicitType.Trill;

					case "turn":
						return ImplicitType.Turn;

					case "mordent":
						return ImplicitType.Mordent;

					case "prall":
						return ImplicitType.Prall;

					// Arpeggio is not implemented in 'articulate.ly' yet
					case "arpeggio":
						return ImplicitType.Arpeggio;
					}
				}
			}
		}

		return ImplicitType.None;
	}


	get clarified (): MusicEvent {
		const clarified = this instanceof Chord ? this.clarifiedChord : this.clone();
		clarified.duration = this.durationValue && this.durationValue.clone();

		return clarified;
	}
};


export class Chord extends MusicEvent {
	pitches: (ChordElement | Command)[];
	options: {
		exclamations?: string[],
		questions?: string[],
		rest?: string,
		withAngle?: boolean,
	};


	constructor (data) {
		super(data);

		this.connectPitches();
	}


	connectPitches () {
		if (this.basePitch)
			this.basePitch._parent = this;
		for (let i = 1; i < this.pitchElements.length; ++i)
			this.pitchElements[i]._previous = this.pitchElements[i - 1];
	}


	get single (): boolean {
		return this.pitches.length === 1;
	}


	get entries () {
		const list: any[] = [...this.pitches];
		if (Array.isArray(this.post_events))
			list.push(...this.post_events);

		return list;
	}


	serialize () {
		const innerPitches = this.pitches.map(BaseTerm.optionalSerialize);
		const pitches = (this.single && !this.options.withAngle) ? cc(innerPitches) : [
			"<", "\b", ...cc(innerPitches), "\b", ">",
		];

		const {exclamations, questions, rest} = this.options;
		const postfix = cc([...(exclamations || []), ...(questions || []), ...BaseTerm.optionalSerialize(this.duration), rest]
			.filter(item => item)
			.map(item => ["\b", item]),
		).concat(...(this.post_events || []).map(BaseTerm.optionalSerialize));

		return [
			new OpenLocator(this),
			...pitches,
			...postfix,
			new CloseLocator(this),
		];
	}


	get pitchElements (): ChordElement[] {
		return this.pitches.filter(pitch => pitch instanceof ChordElement) as ChordElement[];
	}


	get pitchNames (): string[] {
		return this.pitchElements.map((elem: ChordElement) => elem.pitch.replace(/'|,/g, ""));
	}


	get basePitch (): ChordElement {
		return this.pitchElements[0];
	}


	get absolutePitch (): ChordElement {
		console.assert(!!this.basePitch, "absolutePitch on non pitch:", this.join());
		return this.basePitch.absolutePitch;
	}


	get anchorPitch (): ChordElement {
		if (this._anchorPitch)
			return this._anchorPitch;

		const previous = this.getPreviousT(Chord);
		if (previous)
			return previous.absolutePitch;

		return this.basePitch;
	}


	get isRest (): boolean {
		return !!this.options.rest;
	}


	get completeTied (): boolean {
		return this.pitchElements.filter(pitch => !pitch._tied).length === 0;
	}


	get pitchesValue (): (ChordElement | Command)[] {
		if (this._previous instanceof Chord && this.basePitch.pitch === "q") {
			const pitches = this._previous.pitchesValue.map(pitch => {
				const newPitch = pitch.clone();
				if (newPitch instanceof ChordElement) {
					newPitch._location = this.basePitch._location;
					newPitch._tied = this.basePitch._tied;
					newPitch._parent = (pitch as ChordElement)._parent && this;
					newPitch._previous = (pitch as ChordElement)._previous;
				}

				return newPitch;
			});
			const base = pitches.find(pitch => pitch instanceof ChordElement) as ChordElement;
			if (base)
				base.pitch = base.pitch.replace(/[,']/g, "");

			return pitches;
		}

		return this.pitches;
	}


	get clarifiedChord (): MusicEvent {
		const clarified = this.clone();
		clarified.pitches = this.pitchesValue.filter(pitch => !(pitch as ChordElement)._tied).map(pitch => pitch.clone());
		clarified.connectPitches();

		// replace by rest if all pitches tied
		if (!clarified.pitches.length)
			return new Rest({name: "r", duration: this.duration});

		return clarified;
	}


	shiftAnchor (newAnchor: ChordElement) {
		//console.warn("shiftAnchor:", this.join(), newAnchor.join(), this.absolutePitch.pitchValue, newAnchor.pitchValue, this.anchorPitch.pitchValue);
		const _location = this.basePitch._location;
		const shift = idioms.phonetDifferToShift(this.basePitch.phonetStep - newAnchor.phonetStep);
		const relativeOctave = this.basePitch.absoluteOctave(this.anchorPitch) - newAnchor.octave - shift;
		//console.log("_location:", _location);

		this.pitches[0] = ChordElement.from({
			phonet: this.basePitch.phonet,
			alters: this.basePitch.alters,
			octave: relativeOctave,
		});

		this.pitches[0]._location = _location;
		this.pitches[0]._parent = this;

		this.connectPitches();

		//console.log("shiftAnchor.1:", this.join(), this.absolutePitch.pitchValue, {relativeOctave, shift, "newAnchor.octave": newAnchor.octave});
	}


	makeRelativeTo (from: ChordElement) {
		const _location = this.basePitch._location;

		const octave = this.basePitch.relativeOctave(from);
		this.pitches[0] = ChordElement.from({
			phonet: this.basePitch.phonet,
			alters: this.basePitch.alters,
			octave,
		});

		this.pitches[0]._location = _location;
		this.pitches[0]._parent = this;
	}
};


export class Rest extends MusicEvent {
	name: string;


	serialize () {
		return [
			new OpenLocator(this),
			...compact([
				this.name,
				...BaseTerm.optionalSerialize(this.duration),
			]),
			...cc((this.post_events || []).map(BaseTerm.optionalSerialize)),
			new CloseLocator(this),
		];
	}


	get isSpacer () {
		return this.name === "s";
	}


	get isRest (): boolean {
		return true;
	}
};


export class ChordElement extends BaseTerm {
	pitch: string;
	options: {
		exclamations?: string[],
		questions?: string[],
		post_events?: PostEvent[],
	};

	declare _parent?: Chord;
	declare _previous?: ChordElement;
	_tied?: MusicEvent;
	_transposition?: number;

	// cache for property of absolutePitch
	_absolutePitch?: ChordElement;


	static from ({phonet, alters = "", octave, options = {}}): ChordElement {
		const octaveString = octave ? Array(Math.abs(octave)).fill(octave > 0 ? "'" : ",").join("") : "";
		const pitch = phonet + (alters || "") + octaveString;

		return new ChordElement({pitch, options: {...options, proto: "_PLAIN"}});
	}


	static get default (): ChordElement {
		return ChordElement.from({phonet: "c", octave: 0});
	}


	constructor (data: object) {
		super(data);

		if (this.options.post_events)
			this.options.post_events = this.options.post_events.map(parseRaw);

		if (!this.pitch)
			console.log("null pitch:", this);
	}


	serialize () {
		const {exclamations, questions, post_events} = this.options;
		const postfix = [].concat(...[...(exclamations || []), ...(questions || [])]
			.filter(item => item)
			.map(item => ["\b", item]),
		).concat(...(post_events || []).map(item => ["\b", ...BaseTerm.optionalSerialize(item)]));

		return [
			new OpenLocator(this),
			this.pitch,
			...postfix,
			new CloseLocator(this),
		];
	}


	get octave (): number {
		const positive = (this.pitch.match(/'/g) || []).length;
		const negative = (this.pitch.match(/,/g) || []).length;

		return positive - negative;
	}


	get phonet (): string {
		const ph = this.pitch.substr(0, 1);

		return idioms.PHONETS_ALIAS[ph] || ph;
	}


	get phonetStep (): number {
		return idioms.PHONETS.indexOf(this.phonet);
	}


	get alters (): string {
		const captures = this.pitch.substr(1).match(/^\w+/);
		return captures && captures[0];
	}


	get alteredPhonet (): string {
		const captures = this.pitch.match(/^\w+/);
		return captures && captures[0];
	}


	get anchorPitch (): ChordElement {
		if (this._previous)
			return this._previous.absolutePitch;

		if (this._parent)
			return this._parent.anchorPitch;

		return ChordElement.from({phonet: this.phonet, octave: 0});
	}


	getAbsolutePitch (): ChordElement {
		if (this.phonet === "q")
			return this.anchorPitch;

		if (this.anchorPitch === this)
			return this;

		const octave = this.absoluteOctave(this.anchorPitch);

		return ChordElement.from({phonet: this.phonet, alters: this.alters, octave});
	}


	get absolutePitch (): ChordElement {
		if (!this._absolutePitch)
			this._absolutePitch = this.getAbsolutePitch();

		return this._absolutePitch;
	}


	absoluteOctave (anchor: ChordElement): number {
		if (this.phonet === "q")
			return anchor.octave;

		const phonetDiffer = this.phonetStep - anchor.phonetStep;
		const shift = idioms.phonetDifferToShift(phonetDiffer);

		return anchor.octave + shift + this.octave;
	}


	relativeOctave (from: ChordElement): number {
		if (this.phonet === "q") {
			if (this.anchorPitch)
				return this.anchorPitch.relativeOctave(from);
			else
				return 0;
		}

		const phonetDiffer = this.phonetStep - from.phonetStep;
		const shift = idioms.phonetDifferToShift(phonetDiffer);

		return this.octave - shift - from.octave;
	}


	get alterValue (): number {
		return idioms.ALTER_VALUES[this.alters] || 0;
	}


	get pitchValue (): number {
		const phonetValue = idioms.PHONET_VALUES[this.phonet];
		console.assert(Number.isInteger(phonetValue), "invalid phonet:", this.phonet);
		console.assert(!this.alters || idioms.ALTER_VALUES[this.alters], "invalid alters:", this.alters);

		return 48 + this.octave * 12 + phonetValue + this.alterValue;
	}


	get absolutePitchValue (): number {
		return this.absolutePitch.pitchValue;
	}


	// middle C is zero
	get notePosition (): number {
		const phonet = idioms.PHONETS.indexOf(this.phonet);

		return (this.octave - 1) * 7 + phonet;
	}


	get absoluteNotePosition (): number {
		return this.absolutePitch.notePosition;
	}


	get tiedParent (): ChordElement {
		if (!this._tied || !(this._tied instanceof Chord))
			return null;

		const pitch = this._tied.pitchElements.find(p => p.absolutePitchValue === this.absolutePitchValue);
		if (!pitch)
			return null;

		if (pitch._tied)
			return pitch.tiedParent;

		return pitch;
	}
};


export class Duration extends BaseTerm {
	number: string;
	dots: number;
	multipliers?: string[];


	static _default: Duration;
	static get default (): Duration {
		if (!Duration._default)
			Duration._default = new Duration({number: 4, dots: 0});

		return Duration._default;
	}


	static fromMagnitude (magnitude: number): Duration {
		const MULTI = 1024;
		const MULTI_DURATION_MAGNITUDE = WHOLE_DURATION_MAGNITUDE * MULTI;
		const multiMag = magnitude * MULTI;
		if (!Number.isInteger(multiMag)) {
			console.warn("magnitude must be integer:", magnitude);
			return null;
		}

		const di = gcd(multiMag, MULTI_DURATION_MAGNITUDE);
		const denominator = MULTI_DURATION_MAGNITUDE / di;
		const numerator = multiMag / di;
		if (!Number.isInteger(Math.log2(denominator)))
			return new Duration({number: 1, dots: 0, multipliers: [`${numerator}/${denominator}`]});

		switch (numerator) {
		case 1:
			return new Duration({number: denominator, dots: 0});

		case 3:
			return new Duration({number: denominator / 2, dots: 1});

		case 7:
			return new Duration({number: denominator / 4, dots: 2});

		default:
			return new Duration({number: denominator, dots: 0, multipliers: [numerator.toString()]});
		}
	}


	serialize () {
		const dots = Array(this.dots).fill(".").join("");
		const multipliers = this.multipliers && this.multipliers.map(multiplier => `*${multiplier}`).join("");

		return compact([
			this.number, dots, multipliers,
		]);
	}


	get withMultiplier () {
		return this.multipliers && this.multipliers.length > 0;
	}


	get denominator (): number {
		switch (this.number) {
		case "\\breve":
			return 0.5;

		case "\\longa":
			return 0.25;
		}

		return Number(this.number);
	}


	get division (): number {
		return Math.log2(this.denominator);
	}


	// how many smallest rhythm unit in a whole note
	get subdivider (): number {
		return this.denominator * (2 ** this.dots);
	}


	get magnitude (): number {
		let value = WHOLE_DURATION_MAGNITUDE / this.denominator;

		if (this.dots)
			value *= 2 - 0.5 ** this.dots;

		if (this.multipliers)
			this.multipliers.forEach(multiplier => value *= eval(multiplier));

		return value;
	}
};


interface BriefChordBody {
	pitch: string;
	duration: Duration;
	separator: string;
	items: string[];
};


export class BriefChord extends BaseTerm {
	body: BriefChordBody;
	post_events: any[];


	constructor (data: object) {
		super(data);

		if (this.body)
			this.body.duration = parseRaw(this.body.duration);
	}


	serialize () {
		const {pitch, duration, separator, items} = this.body;

		return [
			...compact(cc([pitch, duration, separator, ...(items || [])].map(BaseTerm.optionalSerialize))),
			...cc((this.post_events || []).map(BaseTerm.optionalSerialize)),
		];
	}


	get isMusic (): boolean {
		return true;
	}


	get durationMagnitude (): number {
		if (this.body.duration)
			return this.body.duration.magnitude;

		return 0;
	}
};


export class NumberUnit extends BaseTerm {
	number: number;
	unit: string;


	serialize () {
		return [this.number, "\b", this.unit];
	}


	set ({number, unit}) {
		this.number = Number(number.toFixed(2));

		if (unit !== undefined)
			this.unit = unit;
	}
}


export class Tempo extends BaseTerm {
	beatsPerMinute?: number;
	unit?: Duration;
	text?: string;


	static fromNoteBpm (note: number, bpm: number): Tempo {
		return new Tempo ({
			unit: new Duration({number: note.toString(), dots: 0}),
			beatsPerMinute: bpm,
		});
	}


	serialize () {
		const assignment = Number.isFinite(this.beatsPerMinute) ? [...BaseTerm.optionalSerialize(this.unit), "=", this.beatsPerMinute] : [];

		return [
			"\\tempo",
			...BaseTerm.optionalSerialize(this.text),
			...assignment,
		];
	}
}


const DIRECTION_CHAR = {
	up: "^",
	down: "_",
	middle: "-",
};


export class PostEvent extends BaseTerm {
	direction: string;
	arg: string | BaseTerm;


	serialize () {
		const dir = DIRECTION_CHAR[this.direction];
		const prefix = dir ? [dir, "\b"] : [];

		return prefix.concat(BaseTerm.optionalSerialize(this.arg));
	}


	get entries () {
		if (this.arg instanceof BaseTerm)
			return [this.arg];

		return null;
	}


	get isTying (): boolean {
		return this.arg === "~";
	}


	get isStaccato (): boolean {
		if (this.arg instanceof Command)
			return ["staccato", "staccatissimo", "portato"].includes(this.arg.cmd);

		if ([".", "!"].includes(this.arg as string))
			return true;

		return false;
	}
};


export class Fingering extends BaseTerm {
	value: number;


	serialize () {
		return [this.value];
	}
};


export class Markup extends BaseTerm {
	head: any[];
	body: (string|BaseTerm);


	serialize () {
		return [
			...cc(this.head.map(BaseTerm.optionalSerialize)),
			...BaseTerm.optionalSerialize(this.body),
		];
	}
};


export class Lyric extends MusicEvent {
	content: string | LiteralString;


	serialize () {
		return [
			...BaseTerm.optionalSerialize(this.content),
			...BaseTerm.optionalSerialize(this.duration),
			...cc((this.post_events || []).map(BaseTerm.optionalSerialize)),
		];
	}
};


export class Comment extends BaseTerm {
	text: string;
	scoped: boolean;


	serialize () {
		return [
			this.text,
			"\n",
		];
	}


	static createSingle (text): Comment {
		return new Comment({text: "%" + text});
	}


	static createScoped (text): Comment {
		console.assert(!/%\}/.test(text), "invalid scoped comment text:", text);

		return new Comment({text: `%{${text}%}`, scoped: true});
	}
};


export class Unexpect extends BaseTerm {
	constructor (data) {
		super(data);

		console.warn("unexpected term", data);
	}
};


export const termDictionary = {
	Root,
	LiteralString,
	Command,
	Variable,
	MarkupCommand,
	Repeat,
	Relative,
	ParallelMusic,
	TimeSignature,
	Partial,
	Times,
	Tuplet,
	Grace,
	AfterGrace,
	Clef,
	KeySignature,
	OctaveShift,
	Include,
	Version,
	Language,
	LyricMode,
	ChordMode,
	Transposition,
	StemDirection,
	Change,
	Block,
	InlineBlock,
	Scheme,
	SchemeFunction,
	SchemePair,
	SchemePointer,
	SchemeEmbed,
	Assignment,
	Duration,
	ChordElement,
	Chord,
	Rest,
	BriefChord,
	NumberUnit,
	MusicBlock,
	SimultaneousList,
	ContextedMusic,
	Divide,
	Tempo,
	PostEvent,
	Fingering,
	Markup,
	Lyric,
	Primitive,
	Comment,
};


const termProtoMap: Map<object, string> = Object.entries(termDictionary)
	.reduce((map, [name, cls]: [string, {prototype: object}]) => (map.set(cls.prototype, name), map), new Map());


const parseRawEnforce = data => {
	switch (typeof data) {
	case "string":
	case "number":
		return new Primitive({exp: data});

	default:
		return parseRaw(data);
	}
};


export const parseRaw = data => {
	if (data instanceof BaseTerm)
		return data;

	if (!data)
		return data;

	switch (typeof data) {
	case "object":
		if (Array.isArray(data))
			return data.map(item => parseRaw(item));

		const {proto, ...fields} = data;
		if (proto) {
			if (proto === "_PLAIN")
				return fields;

			const termClass = termDictionary[proto];
			if (!termClass)
				throw new Error(`Unexpected term class: ${data.proto}`);

			return new termClass(fields);
		}

		return new Unexpect(data); 
	}

	return data;
};