summaryrefslogtreecommitdiff
path: root/src/view.c
blob: bd3fbe2fb0112344e642059eeda07f5fdafd8450 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
/* view.c
 * Functions to create a top level Denemo window
 *
 * for Denemo, a gtk+ frontend to GNU Lilypond
 * (c) 2003-2005  Adam Tee (c) 2007, 2008 2009 Richard Shann
 * 
 */

#include <gtk/gtkaccelgroup.h>
#include <string.h>
#include <math.h>
#include "view.h"
#include "bookmarks.h"

#include "lilydirectives.h"
#include "dialogs.h"
#include "utils.h"
#include <stdlib.h>
#include <glib/gstdio.h>
#include <librsvg/rsvg.h>
#include <librsvg/rsvg-cairo.h>

#include "scorewizard.h"
#include "playback.h"
#include "pitchentry.h"
#include "exportlilypond.h"
#include "print.h"
#include "graceops.h"
#include "kbd-custom.h"
#include "keyboard.h"
#include "csoundplayback.h"
#include "exportlilypond.h"
#include "exportmidi.h"
#include "midi.h"
#include "jackmidi.h"
#include "device_manager.h"
#ifdef _HAVE_FLUIDSYNTH_
#include "fluid.h"
#endif
#include "commandfuncs.h"
#include "calculatepositions.h"
#include "http.h"
#include "texteditors.h"
#include "prefops.h"
#define INIT_SCM "init.scm"


static GtkWidget *playbutton;
static GtkWidget *recordbutton;
static GtkWidget *midithrubutton;
static GtkWidget *deletebutton;
static GtkWidget *convertbutton;

static GtkAdjustment *master_vol_adj;
static GtkAdjustment *master_tempo_adj;

static
void select_rhythm_pattern(RhythmPattern *r);
static 
gint insert_pattern_in_toolbar(RhythmPattern *r);
static 
gboolean append_rhythm(RhythmPattern *r,  gpointer fn);
static    
void install_button_for_pattern(RhythmPattern *r, gchar *thelabel);

static void
newtab (GtkAction *action, gpointer param);

static void
closewrapper (GtkAction *action, gpointer param);
static gboolean
close_gui_with_check (GtkAction *action, gpointer param);
static void
openinnew (GtkAction *action, DenemoScriptParam *param);
static void 
create_rhythm_cb (GtkAction* action, gpointer param);
static void
delete_rhythm_cb (GtkAction * action, gpointer param);
static void
toggle_edit_mode (GtkAction * action, gpointer param);
static void
toggle_rest_mode (GtkAction * action, gpointer param);
static void
toggle_rhythm_mode (GtkAction * action, gpointer param);
static void
fetchcommands (GtkAction *action, gpointer param);
static void
morecommands (GtkAction *action, gpointer param);
static void
mycommands (GtkAction *action, gpointer param);
static void
create_window(void);

static gint 
dnm_key_snooper(GtkWidget *grab_widget, GdkEventKey *event);
static void
populate_opened_recent (void);


#ifdef DEVELOPER
#define MUSIC_FONT(a) "music-sign ("a")"
#else
#define MUSIC_FONT(a) "<span  size=\"10000\" face=\"Denemo\">"a"</span>"
#endif

GtkAction *sharpaction, *flataction;



typedef enum 
{
  ACCELS_LOADED = 0x0,
  ACCELS_CHANGED = 0x1<<0,
  EXTRA_ACCELS_ACTIVE = 0x1<<1,
  ACCELS_MAY_HAVE_CHANGED = 0x1<<2
} AccelStatus;


//FIXME remove these - use for the other way... scm_from_locale_stringn (const char *str, size_t len)

static void use_markup(GtkWidget *widget);
static void save_accels (void);

#include "callbacks.h" /* callback functions menuitems that can be called by scheme */
#include <libguile.h>
//#include <guile/gh.h>

#include "scheme_cb.h"




#ifdef DEVELOPER
static FILE *DEV_fp;
#define DEV_CODE  gint idx = lookup_command_from_name(Denemo.map, name+strlen(DENEMO_SCHEME_PREFIX));\
  gchar *tooltip =  (idx<0)? "To be documented":(gchar*)lookup_tooltip_from_idx(Denemo.map, idx);\
  if(!DEV_fp) DEV_fp = fopen("functions.xml", "w");
#endif

static gint scm_eval_status = 0;

static SCM
standard_handler (gchar *data SCM_UNUSED, SCM tag, SCM throw_args SCM_UNUSED)
{
  g_warning ("\nA script error for file/script %s; the throw arguments are\n", data);
  scm_display (throw_args, scm_current_output_port ());
  scm_newline (scm_current_output_port ());
  g_warning ("\nThe tag is\n");
  scm_display (tag, scm_current_output_port ());
  scm_newline (scm_current_output_port ());
  scm_newline (scm_current_output_port ());
  scm_eval_status = -1;
  g_warning ("Undo will be affected\n");
  stage_undo(Denemo.gui->si, ACTION_SCRIPT_ERROR);
  return SCM_BOOL_F;
}

gint eval_file_with_catch(gchar *filename) {
  // scm_c_primitive_load(filename);
  SCM name = scm_from_locale_string(filename);
  scm_eval_status = 0;
  scm_internal_catch (SCM_BOOL_T,
		      (scm_t_catch_body)  scm_primitive_load, (void *) name,
		      (scm_t_catch_handler) standard_handler, (void *) filename);
  return scm_eval_status;
}


gint
call_out_to_guile (const char *script)
{
  scm_eval_status = 0;
  scm_internal_catch (SCM_BOOL_T,
                      (scm_t_catch_body)  scm_c_eval_string, (void *) script,
                      (scm_t_catch_handler) standard_handler, (void *) script);
  return scm_eval_status;
}





//FIXME common up these!!!
void define_scheme_variable(gchar *varname, gchar *value, gchar *tooltip) {

 gchar *def = g_strdup_printf("\"%s\"", value);
 // g_print("Defining %s\n", def);
 scm_c_define(varname, scm_from_locale_string(def));
 g_free(def);
}
void define_scheme_literal_variable(gchar *varname, gchar *value, gchar *tooltip) {
  scm_c_define(varname, scm_from_locale_string(value));
}
void define_scheme_int_variable(gchar *varname, gint value, gchar *tooltip) {
  scm_c_define(varname, scm_int2num(value));
}

void define_scheme_double_variable(gchar *varname, gdouble value, gchar *tooltip) {
  scm_c_define(varname, scm_double2num(value));
}




void define_scheme_bool_variable(gchar *varname, gint value, gchar *tooltip) {
  scm_c_define(varname, SCM_BOOL(value));
}


GError *execute_script_file(gchar *filename) {
  GError *error = NULL;
  gchar *script;
  if(g_file_get_contents (filename, &script, NULL, &error)) {
    call_out_to_guile(script);//FIXME setup error here if non null return
    g_free(script);
  }
  return error;
}

void execute_scheme(GtkAction *action, DenemoScriptParam *param) {
  executeScript();
}

/***************** definitions to implement calling radio/check items from scheme *******************/
#define MODELESS_STRING "Modeless"
#define CLASSICMODE_STRING "ClassicMode"
#define INSERTMODE_STRING "InsertMode"
#define EDITMODE_STRING "EditMode"
#define NOTE_E_STRING "Note"
#define REST_E_STRING "Rest"
#define BLANK_E_STRING "Blank"
#define RHYTHM_E_STRING "Rhythm"
#define ToggleToolbar_STRING "ToggleToolbar"
#define TogglePlaybackControls_STRING "TogglePlaybackToolbar"
#define ToggleMidiInControls_STRING "ToggleMidiInToolbar"

#define ToggleRhythmToolbar_STRING "ToggleRhythmToolbar"
#define ToggleEntryToolbar_STRING  "ToggleEntryToolbar"
#define ToggleActionMenu_STRING  "ToggleActionMenu"
#define ToggleObjectMenu_STRING  "ToggleObjectMenu"
#define ToggleLilyText_STRING  "ToggleLilyText"
#define ToggleScript_STRING  "ToggleScript"

#define ToggleArticulationPalette_STRING  "ToggleArticulationPalette"
#define TogglePrintView_STRING  "TogglePrintView"
#define ToggleLyricsView_STRING  "ToggleLyricsView"
#define ToggleConsoleView_STRING  "ToggleConsoleView"

#define ToggleScoreView_STRING  "ToggleScoreView"
#define ToggleScoreTitles_STRING  "ToggleScoreTitles"
#define QuickEdits_STRING  "QuickEdits"
#define RecordScript_STRING  "RecordScript"


#define ReadOnly_STRING  "ReadOnly"


#define FN_DEF(X) void X##_CB(void) {\
activate_action("/MainMenu/ModeMenu/"X##_STRING);}

 FN_DEF(MODELESS);
 FN_DEF(CLASSICMODE);
 FN_DEF(INSERTMODE);
 FN_DEF(EDITMODE);
 FN_DEF(NOTE_E);
 FN_DEF(REST_E);
 FN_DEF(BLANK_E);
 FN_DEF(RHYTHM_E);

typedef struct cb_string_pairs  { gpointer p; gchar *str;} cb_string_pairs;
cb_string_pairs activatable_commands[] = {
  {MODELESS_CB, MODELESS_STRING},
  {CLASSICMODE_CB, CLASSICMODE_STRING},
  {INSERTMODE_CB, INSERTMODE_STRING},
  {EDITMODE_CB, EDITMODE_STRING},
  {NOTE_E_CB, NOTE_E_STRING},
  {REST_E_CB, REST_E_STRING},
  {BLANK_E_CB, BLANK_E_STRING},
  {RHYTHM_E_CB, RHYTHM_E_STRING}

};

/***************** end of definitions to implement calling radio/check items from scheme *******************/





static void install_scm_function(gchar *name, gpointer callback) {
#ifdef DEVELOPER
  DEV_CODE;
  if(DEV_fp)
    fprintf(DEV_fp, "<listitem>%s one optional parameter: %s </listitem>\n",name, tooltip);
#endif
  scm_c_define_gsubr (name, 0, 1, 0, callback); // one optional parameter

}
static void install_scm_function1(gchar *name, gpointer callback) {
#ifdef DEVELOPER
  DEV_CODE;
  if(DEV_fp)
    fprintf(DEV_fp, "<listitem>%s one required and one optional parameter: %s </listitem>\n",name, tooltip);
#endif
scm_c_define_gsubr (name, 1, 1, 0, callback);

}
static void install_scm_function2(gchar *name, gpointer callback) {
#ifdef DEVELOPER
  DEV_CODE;
  if(DEV_fp)
    fprintf(DEV_fp, "<listitem>%s two parameters: %s </listitem>\n",name, tooltip);
#endif
scm_c_define_gsubr (name, 2, 0, 0, callback);

}

static void install_scm_function3(gchar *name, gpointer callback) {
#ifdef DEVELOPER
  DEV_CODE;
  if(DEV_fp)
    fprintf(DEV_fp, "<listitem>%s three parameters: %s </listitem>\n",name, tooltip);
#endif
scm_c_define_gsubr (name, 3, 0, 0, callback);

}

static void install_scm_function4(gchar *name, gpointer callback) {
#ifdef DEVELOPER
  DEV_CODE;
  if(DEV_fp)
    fprintf(DEV_fp, "<listitem>%s four parameters: %s </listitem>\n",name, tooltip);
#endif
scm_c_define_gsubr (name, 4, 0, 0, callback);

}

#define DENEMO_SCHEME_PREFIX "d-"

#define INSTALL_SCM_FUNCTION(tooltip, name, callback)\
  install_scm_function(name, callback);\
  define_scheme_variable("Help-"name, tooltip, "Value is the help string of the variable");

#define INSTALL_SCM_FUNCTION1(tooltip, name, callback)\
  install_scm_function1(name, callback);\
  define_scheme_variable("Help-"name, tooltip, "Value is the help string of the variable");
#define INSTALL_SCM_FUNCTION2(tooltip, name, callback)\
  install_scm_function2(name, callback);\
  define_scheme_variable("Help-"name, tooltip, "Value is the help string of the variable");
#define INSTALL_SCM_FUNCTION3(tooltip, name, callback)\
  install_scm_function3(name, callback);\
  define_scheme_variable("Help-"name, tooltip, "Value is the help string of the variable");
#define INSTALL_SCM_FUNCTION4(tooltip, name, callback)\
  install_scm_function4(name, callback);\
  define_scheme_variable("Help-"name, tooltip, "Value is the help string of the variable");


#undef DEV_CODE

static SCM scheme_http(SCM hname, SCM page, SCM other, SCM poststr) {
  gchar *name=NULL, *thepage=NULL, *oth=NULL, *post=NULL;
 if(scm_is_string(hname))
     name = scm_to_locale_string(hname);
 if(scm_is_string(page))
     thepage = scm_to_locale_string(page);
 if(scm_is_string(other))
     oth = scm_to_locale_string(other);
 if(scm_is_string(poststr))
     post = scm_to_locale_string(poststr);


 if(name&&thepage&&post&&oth)
   return scm_from_locale_string(post_denemodotorg(name, thepage, oth, post));
 else
  return SCM_BOOL(FALSE);
}

//FIXME inelegant!
static gint interpret_lilypond_notename(gchar *x, gint *mid_c_offset, gint *enshift) {
  // g_print("Mid c offset of %d\n", *x-'c');
  gchar *c;
  gint octave = -1;/* middle c is c' */
  gint accs = 0;

  for(c = x+1;*c;c++){
    if(*c=='i'&& *(c+1)=='s') {
      accs++;
      c++; ;
    } else if(*c=='e'&& *(c+1)=='s') {
      accs--;
      c++;
    } else if (
      *c==',') {
      octave--;
    } else if (*c=='\'') {
	octave++;
    }
  }
  if (*x =='a' || *x=='b')
    octave++;

  *mid_c_offset = *x-'c' + 7*octave;
  *enshift = accs;
  return *mid_c_offset;
}

static gint lilypond_to_enshift(gchar *enshift_name) {
  gint enshift=0;
  gchar *c;
 for(c = enshift_name;*c;c++){
    if(*c=='i'&& *(c+1)=='s') {
      enshift++;
      c++;
    } else if(*c=='e'&& *(c+1)=='s') {
      enshift--;
      c++;
    }
 }
 return enshift;
}

/*
  execute init scripts in system and local directories for menupath
*/
static SCM scheme_execute_init(gchar *menupath) {
  gchar *filename = g_build_filename(get_data_dir(), "actions", "menus", menupath, INIT_SCM, NULL);
  if(g_file_test(filename, G_FILE_TEST_EXISTS)) { 
    g_print("About to load from %s\n", filename);
    eval_file_with_catch(filename);//ret = scm_c_primitive_load(filename);
  }
  g_free(filename);
  filename = g_build_filename(locatedotdenemo(), "actions", "menus", menupath, INIT_SCM, NULL);
  if(g_file_test(filename, G_FILE_TEST_EXISTS)) { 
    g_print("About to load from %s\n", filename);
    eval_file_with_catch(filename);//ret = scm_c_primitive_load(filename);
  }
  g_free(filename);
  return SCM_BOOL(TRUE);
}

void execute_init_scripts(gchar *menupath) {
  (void)scheme_execute_init(menupath);
}

/* called by a script if it requires initialization
 the initialization script is expected to be in init.scm in the menupath of the action that invoked the script*/
static SCM scheme_initialize_script(SCM action_name) {
  SCM ret;
  gint length;
  //FIXME scm_dynwind_begin (0); etc
  gchar *name = scm_to_locale_string(action_name);//scm_dynwind_free (name);
  GtkAction *action = lookup_action_from_name(name);
  if(!action){
    g_warning("Non-existent action %s", name);
    return SCM_BOOL(FALSE);
  }
  gchar *menupath = g_object_get_data(G_OBJECT(action), "menupath");
  ret = scheme_execute_init(menupath);
  return ret;
}

/* pass in a path (from below menus) to a command script. Loads the command from .denemo or system
 *  if it can be found
 * It is used at startup in .denemo files like ReadingNoteNames.denemo
 * which executes
 (d-LoadCommand "MainMenu/Educational/ReadingNoteNames")
 * to ensure that the command it needs is in the command set.
 */
static SCM scheme_load_command(SCM command) {
  gboolean ret;
  //FIXME scm_dynwind_begin (0); etc
  gchar *name = scm_to_locale_string(command);//scm_dynwind_free (name);
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "menus", name, NULL);
  ret = load_xml_keymap(filename, FALSE);
  if(ret==FALSE) {
    g_free(filename);
    filename = g_build_filename(locatedotdenemo(), "download", "actions", name, NULL);
    ret = load_xml_keymap(filename, FALSE);
  }
  if(ret==FALSE) {
    g_free(filename);
    filename = g_build_filename(get_data_dir(), "actions", name, NULL);
    ret = load_xml_keymap(filename, FALSE);
  }
  g_free(filename);
  return SCM_BOOL(ret);
}
static void
toggle_toolbar (GtkAction * action, gpointer param);
static void
toggle_playback_controls (GtkAction * action, gpointer param);
static void
toggle_midi_in_controls (GtkAction * action, gpointer param);
static void
toggle_rhythm_toolbar (GtkAction * action, gpointer param);
static void
toggle_entry_toolbar (GtkAction * action, gpointer param);
static void
toggle_object_menu (GtkAction * action, gpointer param);

static void
toggle_main_menu (GtkAction * action, gpointer param);
static void
toggle_console_view (GtkAction *action, gpointer param);
static void
toggle_print_view (GtkAction *action, gpointer param);
static void
toggle_scoretitles (GtkAction *action, gpointer param);


gint hide_printarea_on_delete(void) {
  activate_action("/MainMenu/ViewMenu/"TogglePrintView_STRING);
  return TRUE;
}
static void
toggle_page_view(void) {
  
  static gdouble zoom=1.0;
  static gdouble system_height=0.25;
  DenemoScore *si = Denemo.gui->si;
  if(si->page_width==0) {
    si->page_width = gdk_screen_get_width(gtk_window_get_screen( GTK_WINDOW (Denemo.window)));
    si->page_height = gdk_screen_get_height(gtk_window_get_screen( GTK_WINDOW (Denemo.window)));
    if(si->page_height/(double)si->page_width < 1.4)
      si->page_width = si->page_height /1.4;
    si->page_zoom = 0.5;
    si->page_system_height = 0.25;
  }
  if(Denemo.gui->view==DENEMO_PAGE_VIEW){
    gtk_window_get_size ( GTK_WINDOW (Denemo.window), &si->page_width, &si->page_height);
    si->page_zoom = si->zoom;
    si->page_system_height = si->system_height;
    si->zoom = zoom;
    si->system_height = system_height;
    Denemo.gui->view=DENEMO_LINE_VIEW;
    gtk_window_resize (GTK_WINDOW (Denemo.window), si->stored_width, si->stored_height);
  } else {
    gtk_window_get_size ( GTK_WINDOW (Denemo.window), &si->stored_width, &si->stored_height);
    zoom = si->zoom;
    system_height = si->system_height;
    si->zoom = si->page_zoom;
    si->system_height = si->page_system_height;
    Denemo.gui->view=DENEMO_PAGE_VIEW;
    gtk_window_resize (GTK_WINDOW (Denemo.window), si->page_width, si->page_height);
  }
}
/* Hide/show everything except the drawing area */
void toggle_to_drawing_area(gboolean show) {
#define current_view Denemo.gui->view   
  gint height;// height of menus that are hidden
  gint win_width, win_height;
  height = 0;

  if(current_view==DENEMO_LINE_VIEW) {
    toggle_page_view();
    return;
  }
  if(current_view==DENEMO_PAGE_VIEW) {
    toggle_page_view();
    win_width = Denemo.gui->si->stored_width;
    win_height = Denemo.gui->si->stored_height;
  } else
    gtk_window_get_size ( GTK_WINDOW (Denemo.window), &win_width, &win_height);
  //g_print("window width is %d\n", win_width);
  // NOTE  lyrics are per movement
  GtkWidget *widget;
  gboolean hide = !show;
  if(((current_view==DENEMO_PAGE_VIEW) && hide) || (show && (!current_view)))
    return;
  current_view = hide?DENEMO_LINE_VIEW:DENEMO_MENU_VIEW;
#define ACCUM height += widget->allocation.height
#define TOG(name, item, menu)\
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, name);\
  static gboolean item=TRUE;\
  if(hide)\
    item = GTK_WIDGET_VISIBLE (widget);\
  if((hide && item) || (show && item))\
    ACCUM, activate_action(menu);

#define TOG2(name, item)\
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, name);\
  static gboolean item=TRUE;\
  if(hide)\
    item = GTK_WIDGET_VISIBLE (widget);\
  if(hide && item)\
    ACCUM, gtk_widget_hide(widget);		\
  if(!hide && item)\
    ACCUM, gtk_widget_show(widget);		  

#define TOG3(name, item, menu)\
  widget = name;\
  static gboolean item=TRUE;\
  if(hide) \
    item = GTK_WIDGET_VISIBLE (widget);\
  if((hide && item) || (show && item))\
    ACCUM, activate_action(menu);

  TOG("/ToolBar", toolbar, "/MainMenu/ViewMenu/"ToggleToolbar_STRING);
  //TOG("/RhythmToolBar", rtoolbar, "/MainMenu/ViewMenu/"ToggleRhythmToolbar_STRING);
  TOG("/ObjectMenu", objectmenu, "/MainMenu/ViewMenu/"ToggleObjectMenu_STRING);

  TOG2("/EntryToolBar", entrymenu);
  TOG2("/MainMenu", mainmenu);

  TOG3(gtk_widget_get_parent(Denemo.console), console_view, "/MainMenu/ViewMenu/"ToggleConsoleView_STRING);
  TOG3(gtk_widget_get_parent(gtk_widget_get_parent(Denemo.printarea)), print_view, "/MainMenu/ViewMenu/"TogglePrintView_STRING);
  TOG3(Denemo.gui->buttonboxes, scoretitles, "/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);
  TOG3(Denemo.playback_control, playback_control, "/MainMenu/ViewMenu/"TogglePlaybackControls_STRING);
  TOG3(Denemo.midi_in_control, midi_in_control, "/MainMenu/ViewMenu/"ToggleMidiInControls_STRING);

  gtk_window_resize (GTK_WINDOW (Denemo.window), win_width, win_height + (current_view?-height:height));
#undef current_view
}

void ToggleReduceToDrawingArea (GtkAction * action, DenemoScriptParam *param) {
  GtkWidget *widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/MainMenu");
  gboolean visibile =  GTK_WIDGET_VISIBLE (widget);
  if(Denemo.gui->view == DENEMO_MENU_VIEW && !visibile){
    g_warning("Out of step");
    Denemo.gui->view == DENEMO_LINE_VIEW;
  }
  toggle_to_drawing_area(!GTK_WIDGET_VISIBLE (widget));
}

/* hide all menus, leaving only the score titles, used for educational games */
static SCM scheme_hide_menus(SCM hide) {
  if(Denemo.gui->view!=DENEMO_MENU_VIEW) {
    activate_action("/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);
    ToggleReduceToDrawingArea(NULL, NULL);
    return  SCM_BOOL(TRUE);
  }
  gboolean show = FALSE;
  if(scm_is_bool(hide) && hide==SCM_BOOL_F)
    show = TRUE;
  toggle_to_drawing_area(show);
  activate_action("/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);
  return SCM_BOOL(TRUE);
}


/* when a script calls a command which is itself a script it comes through here */
static SCM scheme_script_callback(SCM script) {
    int length;
    char *name=NULL;
  //FIXME scm_dynwind_begin (0); etc
   if(scm_is_string(script)){
     name = scm_to_locale_string(script);
     if(name) {
       GtkAction *action = lookup_action_from_name (name);
       if(action){
	 gchar *text = g_object_get_data(G_OBJECT(action), "scheme");
	 if(text && *text)
	   return SCM_BOOL(!call_out_to_guile(text));
	 return SCM_BOOL(activate_script(action, NULL));
       }
     }
   }
return  SCM_BOOL(FALSE);
}
void create_scheme_function_for_script(gchar *name) {
  gchar *proc = g_strdup_printf("(d-%s)", name);
  gchar *value = g_strdup_printf("(d-ScriptCallback \"%s\")", name);
  gchar *def = g_strdup_printf("(define %s %s)\n", proc, value);
  // g_print("Defining %s\n", def);
  call_out_to_guile(def);
  g_free(def);
  // define_scheme_literal_variable(proc, value, "A scheme procedure to call the script of that name");
}


static SCM scheme_debug_object (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;

 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data))
   return SCM_BOOL(FALSE);
 g_print("*************\nType = %d\nbasic_durinticks = %d\ndurinticks - %d\nstarttickofnextnote = %d\n***********\n", 
	 curObj->type,
	 curObj->basic_durinticks,
	 curObj->durinticks,
	 curObj->starttickofnextnote);
 return SCM_BOOL(TRUE);
}


static SCM scheme_load_keybindings (SCM name) {
  gchar * filename;
  if(scm_is_string(name)) {
    filename = scm_to_locale_string(name);
    if(load_xml_keybindings (filename) == 0)
      return SCM_BOOL_T; //FIXME memory leaks on success?
    gchar *name = g_build_filename (locatedotdenemo (), "actions", filename, NULL);
    if(load_xml_keybindings (name) == 0)
      return SCM_BOOL_T;
    g_free(name);
    name = g_build_filename (locatedotdenemo (), "download", "actions", filename, NULL);
    if(load_xml_keybindings (name) == 0)
      return SCM_BOOL_T;
    g_free(name);
    name = g_build_filename (get_data_dir (), "actions", filename, NULL);
    if(load_xml_keybindings (name) == 0)
      return SCM_BOOL_T;
    g_free(name);
  }
  return SCM_BOOL_F;
}

static SCM scheme_save_keybindings (SCM name) {
  gchar * filename;
  if(scm_is_string(name)) {
    filename = scm_to_locale_string(name);
    if(save_xml_keybindings (filename) == 0)
      return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}

static SCM scheme_clear_keybindings (SCM optional) {
  keymap_clear_bindings(Denemo.map);
  return SCM_BOOL_T;
}


static SCM scheme_load_commandset (SCM name) {
  gchar * filename;
  if(scm_is_string(name)) {
    filename = scm_to_locale_string(name);
    if(load_xml_keymap (filename, FALSE) == 0)
      return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}




static SCM scheme_push_clipboard (SCM optional) {
  push_clipboard();
  return SCM_BOOL_T;
}

static SCM scheme_pop_clipboard (SCM optional) {
  if (pop_clipboard())
    return SCM_BOOL_T;
  else
    return SCM_BOOL_F;
}

static SCM scheme_delete_selection(SCM optional) {
  if ((!Denemo.gui->si) || (!Denemo.gui->si->markstaffnum))
    return SCM_BOOL_F;
  delete_selection();
  return SCM_BOOL_T;
}


static SCM scheme_take_snapshot (SCM optional) {   
  return SCM_BOOL(take_snapshot());
}

static SCM scheme_increase_guard (SCM optional) {
 if(Denemo.gui->si->undo_guard++)
  return SCM_BOOL_F;
 return SCM_BOOL_T;
}
static SCM scheme_decrease_guard (SCM optional) {
  if(Denemo.gui->si->undo_guard>0)
    return SCM_BOOL(!--Denemo.gui->si->undo_guard);
  Denemo.gui->si->undo_guard = 0;
  return SCM_BOOL_T;
}

//From a script undo must undo only the modifications to the start of the script, and push another STAGE_END for the end of the actions that it will do after the invocation of undo. This function overrides the built-in undo called directly by the user.
static SCM scheme_undo  (SCM optional) {
  stage_undo(Denemo.gui->si, ACTION_STAGE_START);
  undowrapper(NULL, NULL);
  stage_undo(Denemo.gui->si, ACTION_STAGE_END);
  return SCM_BOOL_T;
}

//Break the script up for undo purposes
static SCM scheme_stage_for_undo (SCM optional) {
  stage_undo(Denemo.gui->si, ACTION_STAGE_START);
  stage_undo(Denemo.gui->si, ACTION_STAGE_END);
  return SCM_BOOL_T;
}


static SCM scheme_new_window  (SCM optional) {
  stage_undo(Denemo.gui->si, ACTION_STAGE_START);

  //gint current =  Denemo.gui->scorearea->allocation.width;
  newview(NULL, NULL);
  // Denemo.gui->scorearea->allocation.width = current;

  stage_undo(Denemo.gui->si, ACTION_STAGE_END);
  return SCM_BOOL_T;
}


static SCM scheme_zoom (SCM factor) {
  if(scm_is_real(factor))
    Denemo.gui->si->zoom = scm_to_double(factor);
  else if(scm_is_string(factor)) {
    gchar *name = scm_to_locale_string(factor);
    if(name)
      Denemo.gui->si->zoom = atof(name);
  } else {
    return scm_double2num(Denemo.gui->si->zoom);
  }
     
  scorearea_configure_event(Denemo.scorearea, NULL);
  if(Denemo.gui->si->zoom > 0.01)
    return  scm_int2num(Denemo.gui->si->zoom);
    Denemo.gui->si->zoom =  1.0;
    return SCM_BOOL_F;
}

static SCM scheme_master_tempo (SCM factor) {
  DenemoScore *si = Denemo.gui->si;
  gdouble request_time = get_time();
  gdouble duration = request_time - si->tempo_change_time;
  si->start_player += duration*(1.0-si->master_tempo);

  if(scm_is_real(factor))
    si->master_tempo = scm_to_double(factor);
  else if(scm_is_string(factor)) {
    gchar *name = scm_to_locale_string(factor);
    if(name)
     si->master_tempo = atof(name);
  } else 
  return scm_double2num(si->master_tempo);
  if(si->master_tempo < 0.0)
    si->master_tempo =  1.0;
  
  si->tempo_change_time = request_time;
  return scm_double2num(si->master_tempo);
}

static SCM scheme_movement_tempo (SCM bpm) {
  DenemoScore *si = Denemo.gui->si;
  if(scm_is_real(bpm))
    si->tempo = scm_to_int(bpm);
  if(scm_is_string(bpm)) {
    gchar *name = scm_to_locale_string(bpm);
    if(name)
     si->tempo = atof(name);
  }

  if(si->tempo < 1)
    si->tempo =  120;
  return scm_int2num(si->tempo);
}

static SCM scheme_master_volume (SCM factor) {
  DenemoScore *si = Denemo.gui->si;
  if(scm_is_real(factor))
    si->master_volume = scm_to_double(factor);
  if(scm_is_string(factor)) {
    gchar *name = scm_to_locale_string(factor);
    if(name)
     si->master_volume = atof(name);
  }
  if(si->master_volume < 0.0)
    si->master_volume =  1.0;
  return scm_double2num(si->master_volume);
}

static SCM scheme_get_midi_tuning(void) {
  gchar *cents = get_cents_string();
  SCM ret = scm_makfrom0str (cents);
  g_free(cents);
  return ret;
}
static SCM scheme_get_sharpest(void) {
  gchar *name = get_sharpest();
  SCM ret = scm_makfrom0str (name);
  g_free(name);
  return ret;
}
static SCM scheme_get_flattest(void) {
  gchar *name = get_flattest();
  SCM ret = scm_makfrom0str (name);
  g_free(name);
  return ret;
}
static SCM scheme_get_temperament(void) {
  gchar *name = get_temperament_name();
  SCM ret = scm_makfrom0str (name);
  g_free(name);
  return ret;
}

static SCM scheme_set_enharmonic_position(SCM position) {
  if(scm_integer_p(position)) {
     gint pos = scm_num2int(position, 0, 0);
     set_enharmonic_position(pos);
     return SCM_BOOL_T;
    }
    return SCM_BOOL_F;		      
}


static SCM scheme_get_midi_on_time(void) {
  if(!(Denemo.gui->si->currentobject))
    return SCM_BOOL_F;
  DenemoObject *curobj = Denemo.gui->si->currentobject->data;
  if(!curobj->midi_events)
    return SCM_BOOL_F;
  return scm_double2num(get_midi_on_time(curobj->midi_events));
}

static SCM scheme_get_midi_off_time(void) {
  if(!(Denemo.gui->si->currentobject))
    return SCM_BOOL_F;
  DenemoObject *curobj = Denemo.gui->si->currentobject->data;
  if(!curobj->midi_events)
    return SCM_BOOL_F;
  return scm_double2num(get_midi_off_time(curobj->midi_events));
}

static SCM scheme_set_playback_interval (SCM start, SCM end) {
  if(scm_is_real(start) && scm_is_real(end) ) {
    Denemo.gui->si->start_time = scm_to_double(start);
    Denemo.gui->si->end_time = scm_to_double(end);
    return SCM_BOOL_T;
  }
  if(scm_is_real(start)){
    Denemo.gui->si->start_time = scm_to_double(start);
    return SCM_BOOL_T;
  }
  if(scm_is_real(end) ) {
    Denemo.gui->si->end_time = scm_to_double(end);
    return SCM_BOOL_T;
  }
  if(scm_is_string(start) && scm_is_string(end) ) {
    gchar *name = scm_to_locale_string(start);
    if(name)
     Denemo.gui->si->start_time = atof(name);
    name = scm_to_locale_string(end);
    if(name)
      Denemo.gui->si->end_time = atof(name);
    return SCM_BOOL_T;
  }
  if(scm_is_string(start)){
    gchar *name = scm_to_locale_string(start);
    if(name)
      Denemo.gui->si->start_time = atof(name);
    return SCM_BOOL_T;
  }
  if(scm_is_string(end) ) {
    gchar *name = scm_to_locale_string(end);
    if(name)
      Denemo.gui->si->end_time = atof(name);
    return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}

static SCM scheme_adjust_playback_start(SCM adj) {
  if(scm_is_real(adj)){
    Denemo.gui->si->start_time += scm_to_double(adj);
    if(Denemo.gui->si->start_time<0.0)
      Denemo.gui->si->start_time = 0.0;
    else
      return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}

static SCM scheme_adjust_playback_end(SCM adj) {
  if(scm_is_real(adj)){
    Denemo.gui->si->end_time += scm_to_double(adj);
    if(Denemo.gui->si->end_time<0.0)
      Denemo.gui->si->end_time = 0.0;
    else
      return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}


static SCM scheme_get_help(SCM command) {
  gchar *name;
  if(scm_is_string(command))
     name = scm_to_locale_string(command);
  if(name==NULL)
    return SCM_BOOL_F;
  gint idx = lookup_command_from_name(Denemo.map, name);

  if(idx<0) {
#if 0
    SCM help = scm_c_eval_string(g_strconcat("Help-d-", name));
    return help;
#else
    return SCM_BOOL_F;
#endif
  }
  return scm_makfrom0str ((gchar*)lookup_tooltip_from_idx(Denemo.map, idx));
}

static SCM scheme_get_lily_version(SCM optional) {
  gchar *version = get_lily_version_string ();
  return scm_makfrom0str (version);
}

static SCM scheme_check_lily_version(SCM check_version) {
  gchar *version;
 if(scm_is_string(check_version))
   version = scm_to_locale_string(check_version);
 else
   return  SCM_BOOL_F;
  gint result = check_lily_version (version);
  if(result>0)
    return SCM_BOOL_T;
  else
    return SCM_BOOL_F;
}

static SCM scheme_get_id(SCM command) {
  gchar *name;
  if(scm_is_string(command)) {
    gint id;
    name = scm_to_locale_string(command);
    id = lookup_command_from_name(Denemo.map, name);
    if(id!=-1)
      return scm_int2num (id);
  }
  return SCM_BOOL_F;
}
static SCM scheme_add_keybinding (SCM command, SCM binding) {
  gchar * shortcut;
  
  gint id;
  gint old_id = -1;
  if(scm_is_string(binding)) {
    shortcut = scm_to_locale_string(binding);
    if(scm_is_string(command)) {
      gchar *name = scm_to_locale_string(command);
      old_id = add_keybinding_for_name(name, shortcut);
    } else if(scm_integer_p(command)) {
      id = scm_to_int(command);
      if(id>=0)
	old_id = add_keybinding_for_command(id, shortcut);	
    }
  }
  if(old_id>=0)
    return scm_int2num(old_id);
  else
    return SCM_BOOL_F;
}

static SCM scheme_get_label(SCM command) {
  gchar *name;
  if(scm_is_string(command))
     name = scm_to_locale_string(command);
  else
    return SCM_BOOL_F;
  if(name==NULL)
    return SCM_BOOL_F;
  gint idx = lookup_command_from_name(Denemo.map, name);
  if(idx<0)
    return SCM_BOOL_F;
  return scm_makfrom0str ((gchar*)lookup_label_from_idx(Denemo.map, idx));
}

static SCM scheme_get_menu_path(SCM command) {
  gchar *name;
  if(scm_is_string(command))
     name = scm_to_locale_string(command);
  else
    return SCM_BOOL_F;
  if(name==NULL)
    return SCM_BOOL_F;
  gint idx = lookup_command_from_name(Denemo.map, name);
  if(idx<0)
    return SCM_BOOL_F;
  GtkAction *action = (GtkAction *)lookup_action_from_idx(Denemo.map, idx);
  if(action==NULL)
    return SCM_BOOL_F;
  gchar *menupath = g_object_get_data(G_OBJECT(action), "menupath");
  if(menupath==NULL)
    return SCM_BOOL_F;
  return scm_makfrom0str (menupath);
}



/* write MIDI/Audio filter status */
static SCM scheme_input_filter_names(SCM filtername) {
    int length;
    char *name=NULL;
  //FIXME scm_dynwind_begin (0); etc
   if(scm_is_string(filtername)){
     name = scm_to_locale_string(filtername);
     if(name) {
       if(Denemo.input_filters)
	 g_string_assign(Denemo.input_filters, name);
       else
	 Denemo.input_filters = g_string_new(name);
       write_input_status();
       return SCM_BOOL(TRUE);
     }
   }  else
    return SCM_BOOL_F;
   if(Denemo.input_filters)
     g_string_free(Denemo.input_filters, TRUE);
   Denemo.input_filters = NULL;
   return  SCM_BOOL(FALSE);
}

SCM scheme_goto_position (SCM movement, SCM staff, SCM measure, SCM object) {
  gint  movementnum, staffnum, measurenum, objectnum;
  if(scm_is_integer(movement))
    movementnum = scm_to_int(movement);
  else
     movementnum = g_list_index(Denemo.gui->movements, Denemo.gui->si)+1;
  if(scm_is_integer(staff))
    staffnum = scm_to_int(staff);
  else
    staffnum = Denemo.gui->si->currentstaffnum;

  if(scm_is_integer(measure))
    measurenum = scm_to_int(measure);
  else
    measurenum = Denemo.gui->si->currentmeasurenum;

  if(scm_is_integer(object))
    objectnum = scm_to_int(object);
  else
    objectnum = 1 + Denemo.gui->si->cursor_x;
  #if 0
  // 1 is ambiguous, either empty measure or object 1
  gboolean result = goto_movement_staff_obj (NULL, movementnum, staffnum, measurenum, objectnum);
  if(Denemo.gui->si->currentmeasure->data==NULL && objectnum==1)
    return SCM_BOOL(goto_movement_staff_obj (NULL, movementnum, staffnum, measurenum, 0));
  gint numobjs = (Denemo.gui->si->currentmeasure->data)?g_list_length(Denemo.gui->si->currentmeasure->data):0;
  if(objectnum==1+numobjs)
    Denemo.gui->si->cursor_appending = TRUE;
  write_status(Denemo.gui);
  if(objectnum>1+numobjs)
    return SCM_BOOL_F;
  return SCM_BOOL (result);
#endif
  gint origmvt  = g_list_index(Denemo.gui->movements, Denemo.gui->si)+1,
    origstaff = Denemo.gui->si->currentstaffnum,
    origmeas = Denemo.gui->si->currentmeasurenum,
    origpos = 1 + Denemo.gui->si->cursor_x ;
  gboolean result = goto_movement_staff_obj (NULL, movementnum, staffnum, measurenum, objectnum);
  if((movementnum == g_list_index(Denemo.gui->movements, Denemo.gui->si)+1) &&
     (staffnum ==  Denemo.gui->si->currentstaffnum) &&
     (measurenum ==  Denemo.gui->si->currentmeasurenum) &&
     (objectnum == 1 + Denemo.gui->si->cursor_x))
    return SCM_BOOL_T;
  else
    goto_movement_staff_obj (NULL,origmvt, origstaff, origmeas, origpos);
     
  return SCM_BOOL_F;
}

SCM scheme_shift_cursor (SCM value) {
  if(!scm_integer_p(value))
    return SCM_BOOL_F;
  gint shift = scm_num2int(value, 0, 0);
  Denemo.gui->si->cursor_y += shift;
  Denemo.gui->si->staffletter_y = offsettonumber(Denemo.gui->si->staffletter_y + shift);
  return SCM_BOOL_T;



}


static SCM scheme_get_horizontal_position(void) {
return  scm_int2num(1 + Denemo.gui->si->cursor_x);
}

static SCM scheme_get_movement(void) {
  gint num = g_list_index(Denemo.gui->movements, Denemo.gui->si)+1;
  return  scm_int2num(num);
}

static SCM scheme_get_staff(void) {
  gint num = Denemo.gui->si->currentstaffnum;
  return  scm_int2num(num);
}

static SCM scheme_get_measure(void) {
  gint num = Denemo.gui->si->currentmeasurenum;
  return  scm_int2num(num);
}

static SCM scheme_get_cursor_note (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 SCM scm = scm_makfrom0str (g_strdup_printf("%c", mid_c_offsettoname (gui->si->cursor_y)));//FIXME a dedicated function avoiding memory leak.
   return scm;
}

static SCM scheme_set_prefs (SCM xml) {
  DenemoGUI *gui = Denemo.gui;
  if(scm_is_string(xml)){ 
    gchar *xmlprefs = scm_to_locale_string(xml);
    gint fail = readxmlprefsString(xmlprefs);
    return SCM_BOOL(!fail);     
  }
  return SCM_BOOL(FALSE);
}

SCM scheme_attach_quit_callback (SCM callback) {
  DenemoGUI *gui = Denemo.gui;
  if(scm_is_string(callback)){ 
    gchar *scheme = scm_to_locale_string(callback);
    gui->callbacks = g_list_prepend(gui->callbacks, scheme);
  }
  return SCM_BOOL(TRUE);
}
SCM scheme_detach_quit_callback (void) {
  DenemoGUI *gui = Denemo.gui;
  if( gui->callbacks) {
    g_free(gui->callbacks->data);
    gui->callbacks = g_list_delete_link(gui->callbacks, gui->callbacks);
    return SCM_BOOL(TRUE);
  } else
    g_warning("No callback registered");
  return SCM_BOOL(FALSE);
}

SCM scheme_chordize (SCM setting) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  chord *thechord;
  note *thenote;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
    return SCM_BOOL(FALSE);
  gboolean val;
  if(SCM_BOOLP(setting)){
    val = scm_to_bool(setting);
  }
  if( thechord->chordize != val) {
    thechord->chordize = val;
    score_status(gui, TRUE);
  }
  return SCM_BOOL(TRUE);
}


SCM scheme_get_note_name (SCM optional) {
    int length;
    //char *str=NULL;
   //if(scm_is_string(optional)){
   //str = scm_to_locale_stringn(optional, &length);
   //  }
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
   SCM scm = scm_makfrom0str (g_strdup_printf("%c",  mid_c_offsettoname (thenote->mid_c_offset)));//FIXME a dedicated function avoiding memory leak.
   return scm;
 }
   
}

//Insert rests to the value of the timesig and return the number of rests inserted.
SCM scheme_put_whole_measure_rests (void) {
  DenemoGUI *gui = Denemo.gui;
  SCM scm;
  if(!Denemo.gui || !(Denemo.gui->si))
    return SCM_MAKINUM(0);
  else {
    DenemoStaff *staff = (DenemoStaff *) gui->si->currentstaff->data;
    gint numerator = gui->si->cursortime1;// staff->timesig.time1;
    gint denominator = gui->si->cursortime2;//staff->timesig.time2;
    gboolean dot = TRUE;
    if(numerator%3)
      dot = FALSE;
    else
      numerator = 2*numerator/3;
    gint length = (numerator*4)/denominator;
    gchar *str=NULL;
    scm = SCM_MAKINUM(1);
    switch(length){
    case 1: // e.g.  2/8 timesig
      str = g_strdup_printf("(d-InsertRest2)(d-MoveCursorLeft)%s", dot?"(d-AddDot)":"");
      break;
    case 2:
      str = g_strdup_printf("(d-InsertRest1)(d-MoveCursorLeft)%s", dot?"(d-AddDot)":"");
      break;
    case 3:// e.g. 9/8 timesig
      str = g_strdup_printf("(d-InsertRest0)(d-InsertRest3)(d-MoveCursorLeft)(d-MoveCursorLeft)");
      scm = SCM_MAKINUM(2);
      break;
    case 4:
      str = g_strdup_printf("(d-InsertRest0)(d-MoveCursorLeft)%s", dot?"(d-AddDot)":"");
      break;
    case 8:
      str = g_strdup_printf("(d-InsertRest0)(d-InsertRest0)(d-MoveCursorLeft)%s", dot?"(d-AddDot)":"");
      scm = SCM_MAKINUM(2);
      break;   
    default:
      g_warning("Not implemented %d %s", length, dot?"dotted":"");
      scm = SCM_MAKINUM(0);
      break;  
    }  
    if(str) {
      call_out_to_guile(str);
    }
    g_free(str);
    return scm;
  }
}

SCM scheme_get_dots(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 gint duration;
 gint numdots = 0;
 gchar *str;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object))
   return  SCM_BOOL_F;
 return scm_int2num(thechord->numdots);
}

SCM scheme_get_note_duration(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 gint duration;
 gint numdots = 0;
 gchar *str;
  
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object))
   return  SCM_BOOL_F;
 if(thechord->baseduration>=0) {
   duration = 1 << thechord->baseduration;
   str = g_strdup_printf("%d", duration);
   if (thechord->numdots)
     while (numdots++ < thechord->numdots)
       str = g_strdup_printf("%s""%c", str, '.');
   
   SCM scm = scm_makfrom0str (str);
   g_free(str);
   return  scm;
 }
 return  SCM_BOOL_F; 
}
static SCM scheme_set_duration_in_ticks(SCM duration){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 gint thedur=0;
 if(scm_is_integer(duration)) {
     thedur =  scm_to_int(duration);
   }
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data))
   return SCM_BOOL_F;
 if(thedur>0) {
   curObj->basic_durinticks = curObj->durinticks = thedur;  
   if(curObj->type==CHORD) {
     ((chord *)curObj->object)->baseduration = -thedur;
     ((chord *)curObj->object)->numdots = 0;
   }
   objnode *prev = Denemo.gui->si->currentobject->prev;
   DenemoObject *prevObj = prev?(DenemoObject *)prev->data:NULL;
   gint starttick = (prevObj?prevObj->starttickofnextnote:0);
   curObj->starttickofnextnote = starttick + thedur;
   return SCM_BOOL_T;
 }
 return SCM_BOOL_F;
}

static SCM scheme_get_onset_time(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 if((Denemo.gui->si->currentobject) && (curObj = Denemo.gui->si->currentobject->data))
   if((gui->si->smfsync == gui->si->changecount)) {
     if(curObj->midi_events) {
       smf_event_t *event = (smf_event_t*)curObj->midi_events->data;
       gdouble time = event->time_seconds;
       return scm_double2num(time);
     }
   }
 return SCM_BOOL_F;
}




static SCM scheme_get_duration_in_ticks(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data))
   return SCM_BOOL(FALSE);
 return scm_int2num(curObj->durinticks);
}

static SCM scheme_get_base_duration_in_ticks(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data))
   return SCM_BOOL(FALSE);
 if(curObj->type==CHORD)
   return scm_int2num(  ((chord *)curObj->object)->baseduration>=0? /* (* (expt 2 (- 8 number)) 6) */
			(int)pow(2.0, (8.0-((chord *)curObj->object)->baseduration))*6: ((chord *)curObj->object)->baseduration
 );
 return SCM_BOOL(FALSE);
}


SCM scheme_get_end_tick(void){
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data))
   return SCM_BOOL(FALSE);
 return scm_int2num(curObj->starttickofnextnote);
}





SCM scheme_get_measure_number(void){
 DenemoGUI *gui = Denemo.gui;
 return scm_int2num(Denemo.gui->si->currentmeasurenum);
}




SCM scheme_get_note (SCM optional) {
  //int length;
    //   char *str=NULL;
    //if(scm_is_string(optional)){
    //str = scm_to_locale_stringn(optional, &length);
    //  }
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
   SCM scm = scm_makfrom0str (g_strdup_printf("%s",  mid_c_offsettolily (thenote->mid_c_offset, thenote->enshift)));//FIXME a dedicated function avoiding memory leak.
   return scm;
 }
   
}

SCM scheme_get_cursor_note_as_midi (SCM optional) {

 DenemoGUI *gui = Denemo.gui;
 gint midi = dia_to_midinote (gui->si->cursor_y);
   SCM scm = scm_int2num (midi);
   return scm;
}


SCM scheme_get_note_as_midi(void) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return scm_int2num (0);
 else {
   gint midi = dia_to_midinote (thenote->mid_c_offset) + thenote->enshift;
   SCM scm = scm_int2num (midi);
   return scm;
   }
}


SCM scheme_get_notes (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 GString *str = g_string_new("");
 SCM scm;

 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
   GList *g;
   for(g=thechord->notes;g;g=g->next) {
     thenote =  (note *) g->data;
     gchar *name =  mid_c_offsettolily (thenote->mid_c_offset, thenote->enshift);
     str =  g_string_append(str,  name);
     if (g->next)
       str =  g_string_append(str,  " ");
   }

   scm = scm_from_locale_string(g_string_free(str, FALSE));
   return scm;
 } 
}

SCM scheme_add_movement(SCM optional) {
  append_blank_movement();
  return SCM_BOOL_T;
}

SCM scheme_get_prevailing_clef(SCM optional) {
  gint theclef = find_prevailing_clef(Denemo.gui->si);
  //FIXME look at directives to see if it is overridden, e.g. drum clef
  const gchar *clefname = get_clef_name(theclef);
  if(clefname)
    return scm_from_locale_string(clefname);
  else return SCM_BOOL_F;
}


SCM scheme_get_prevailing_duration(SCM optional) {
  return scm_int2num(get_prevailing_duration());
}

SCM scheme_get_prevailing_keysig(SCM optional) {
 GString *str = g_string_new(" ");
 keysig *keysig = get_prevailing_context(KEYSIG);
 gint i;
 for(i=0;i<7;i++) g_string_append_printf(str, "%d ", keysig->accs[i]);
 return scm_from_locale_string(g_string_free(str, FALSE));
}

SCM scheme_set_prevailing_keysig(SCM keyaccs) {
  //keysigs have a field called "number" which determines how it is drawn, setting like this does not get a keysig drawn, nor does it affect lilypond output
  gchar *accs=NULL;
  if(scm_is_string(keyaccs)){ 
    accs = scm_to_locale_string(keyaccs);
  }
  if(!accs)
    return SCM_BOOL_F;
  keysig *keysig = get_prevailing_context(KEYSIG);
  sscanf(accs, "%d%d%d%d%d%d%d", keysig->accs+0,keysig->accs+1,keysig->accs+2,keysig->accs+3,keysig->accs+4,keysig->accs+5,keysig->accs+6);
  showwhichaccidentalswholestaff ((DenemoStaff *) Denemo.gui->si->currentstaff->
				  data);
  displayhelper (Denemo.gui);//score_status(Denemo.gui, TRUE);
  return SCM_BOOL_T;
}


SCM scheme_cursor_to_note (SCM lilyname) {
 DenemoGUI *gui = Denemo.gui;
 gint mid_c_offset;
 gint enshift;
 gchar *notename;
 gint dclef;

 if(scm_is_string(lilyname)){ 
   notename = scm_to_locale_string(lilyname);
   interpret_lilypond_notename(notename, &mid_c_offset, &enshift);
   dclef =  find_prevailing_clef(gui->si);
   gui->si->cursor_y = mid_c_offset;
   gui->si->staffletter_y = offsettonumber (gui->si->cursor_y);
   displayhelper (gui);
   return  SCM_BOOL(TRUE);
 }
 else
   return  SCM_BOOL(FALSE);
}

SCM scheme_change_chord_notes (SCM lilynotes) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 gchar *notename;
 gchar *chordnote;
 gint mid_c_offset;
 gint enshift;
 gint dclef;
 GList *g = NULL;
 GList *n = NULL;
 GList *directives = NULL;

 if (scm_is_string(lilynotes)) {
  
   if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return  SCM_BOOL(FALSE);
   
   else {
	/* delete all chord tones */
	while(thechord->notes){
	  thenote = thechord->notes->data;
	  g = g_list_append(g, thenote->directives);	 
	  thenote->directives = NULL;
	  delete_chordnote (gui);
	}
	/* add changed tones */
	dclef =  find_prevailing_clef(Denemo.gui->si);
        notename = scm_to_locale_string(lilynotes);	
	chordnote = strtok(notename, " ");
	while (chordnote){
	  interpret_lilypond_notename(chordnote, &mid_c_offset, &enshift);
	  dnm_addtone (curObj, mid_c_offset, enshift, dclef);
	  chordnote = strtok( NULL, " " );
	}
	/* paste directives over */
	for(n=thechord->notes;n &&g;n=n->next, g=g->next) {
	  thenote = (note *) n->data;
	  directives = (GList *) g->data;

	  if (directives)
	    thenote->directives = directives;
	  
	}
	score_status(gui, TRUE);
	displayhelper (gui);
	return  SCM_BOOL(TRUE);
   }  
 } 
 else
   return  SCM_BOOL(FALSE);
}

SCM scheme_get_user_input(SCM label, SCM prompt, SCM init) {
  gchar *title, *instruction, *initial_value;
  gint length;
  //FIXME scm_dynwind_begin (0);

if(scm_is_string(label)){
  title = scm_to_locale_string(label);
  //scm_dynwind_free (title);
  }
 else title = "Input Required";
 if(scm_is_string(prompt)){
  instruction = scm_to_locale_string(prompt);
  //scm_dynwind_free (instruction);
  }
 else instruction = "Give input: ";

 if(scm_is_string(init)){
  initial_value = scm_to_locale_string(init);
  //scm_dynwind_free (initial_value);
  }
 else initial_value = " ";//FIXME mixed types of string, memory leaks
 
 gchar * ret = string_dialog_entry_with_widget (Denemo.gui, title, instruction, initial_value, NULL);
 SCM scm = scm_makfrom0str (ret);
 //scm_dynwind_end ();
 return scm;
}


SCM scheme_warningdialog(SCM msg) {
  gchar *title;
  gint length;
if(scm_is_string(msg)){
  title = scm_to_locale_string(msg);//scm_dynwind_free (title)
  }
 else title = "Script generated warning";//FIXME mixed types of string, memory leaks
 
 warningdialog (title);
 //scm_dynwind_end ();
 return msg;
}

SCM scheme_infodialog(SCM msg) {
  gchar *title;
  gint length;
if(scm_is_string(msg)){
  title = scm_to_locale_string(msg);//scm_dynwind_free (title)
  msg = SCM_BOOL(TRUE);
  }
 else {
   title = "Script error, wrong parameter type to d-InfoDialog";//FIXME mixed types of string, memory leaks
   msg = SCM_BOOL(FALSE);
 }
 infodialog (title);
 //scm_dynwind_end ();
 return msg;
}

SCM scheme_progressbar(SCM msg) {
  gchar *title;
  if(scm_is_string(msg)){
    title = scm_to_locale_string(msg);//scm_dynwind_free (title)
    progressbar(title);
    msg = SCM_BOOL(TRUE);
  }
  else 
   msg = SCM_BOOL(FALSE);
  
  return msg;
}

SCM scheme_progressbar_stop(void) {
  progressbar_stop();
  return SCM_BOOL(TRUE);
}

SCM scheme_get_char(void) {

  GdkEventKey event;
 gboolean success = intercept_scorearea_keypress(&event);
 if(success) {
 gchar *str = g_strdup_printf("%c", success?event.keyval:0);
 SCM scm = scm_makfrom0str (str);
 g_free(str);
 return  scm;
 }
 else
   return SCM_BOOL(FALSE);
}

SCM scheme_get_keypress(void) {
 GdkEventKey event;
 gboolean success =  intercept_scorearea_keypress(&event);
 if(success) {
 gchar *str = dnm_accelerator_name(event.keyval, event.state);
 SCM scm = scm_makfrom0str (str);
 g_free(str);
 return  scm;
 }
 else
   return SCM_BOOL(FALSE);
}

/* get last keypress that successfully invoked a command */
SCM scheme_get_command_keypress(void) {
 gchar *str = dnm_accelerator_name(Denemo.last_keyval, Denemo.last_keystate);
 SCM scm = scm_makfrom0str (str);
 g_free(str);
 return  scm;
}



SCM scheme_get_command(void) {
  GdkEventKey event;
 GString *name=g_string_new("");
 gboolean success = intercept_scorearea_keypress(&event);
 if(success) {
   gint cmd = lookup_command_for_keyevent (&event);
   //g_print("command %d for %x %x\n", cmd, event.keyval, event.state);
   if(cmd!=-1)
     name = g_string_append(name, lookup_name_from_idx (Denemo.map, cmd));//FIXME NULL?, memory leaks
   name = g_string_prepend (name, DENEMO_SCHEME_PREFIX);
  }
 SCM scm = success? scm_makfrom0str (name->str): SCM_BOOL(FALSE);
 g_string_free(name, TRUE);
 return  scm;
}


gchar *return_command(gchar *name, GdkEvent *event) {
  return name;
}
/* listens for a shortcut and returns a command, or if keypresses are not shortcut returns #f */
SCM scheme_get_command_from_user(void) {
  
  GdkEventKey event;
  
  if(intercept_scorearea_keypress(&event) ) {
    gchar *command = process_key_event(&event, &return_command);
    if(command==NULL)
      return SCM_BOOL_F;
    if(*command==0) {//can be two-key shortcut
      if(intercept_scorearea_keypress(&event)) {
	command = process_key_event(&event, &return_command);
	if(command==NULL)
	  return SCM_BOOL_F;
      } else
	return SCM_BOOL_F;
    }
    write_status(Denemo.gui);
    SCM scm =  scm_makfrom0str (command);//command is from lookup_name_from... functions, do not free.
    return scm;
  }
  return SCM_BOOL_F;
}



static void get_drag_offset(GtkWidget *dialog, gint response_id, GtkLabel *label) {
  g_object_set_data(G_OBJECT(dialog), "offset-response", (gpointer)(intptr_t)response_id);
  if(response_id < 0)
    gtk_main_quit();
  gint offsetx, offsety;
  offsetx =  (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "offsetx");
  offsety =  (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "offsety");
  gchar *text = g_strdup_printf("Offset now %d %d. Drag again in the print window to change\nOr click OK to apply the position shift", offsetx, offsety);
  gtk_label_set_text(label, text);
  g_free(text);
}

static void get_drag_pad(GtkWidget *dialog, gint response_id, GtkLabel *label) {
  g_object_set_data(G_OBJECT(dialog), "pad-response", (gpointer)(intptr_t)response_id);
  if(response_id < 0)
    gtk_main_quit();
  gint padding;
  padding =  (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "padding");
  gchar *text = g_strdup_printf("Padding now %d. Drag again in the print window to change\nOr click OK to apply the padding to the graphical object belonging to the directive", padding);
  gtk_label_set_text(label, text);
  g_free(text);
}



/* return a pair x, y representing the offset desired for some lilypond graphic
 or #f if no printarea or user cancels*/
SCM scheme_get_offset(void) {
  SCM x, y, ret;
  if(Denemo.printarea==NULL)
    return SCM_BOOL(FALSE);
  if(g_object_get_data(G_OBJECT(Denemo.printarea), "offset-dialog")){
    warningdialog("Already in a padding dialog");
    return SCM_BOOL_F;
  }
  gint offsetx = (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "offsetx");
  gint offsety = (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "offsety");


  GtkWidget *dialog = gtk_dialog_new_with_buttons ("Select Offset in Print Window",
                                        GTK_WINDOW (Denemo.window),
                                        (GtkDialogFlags) (GTK_DIALOG_DESTROY_WITH_PARENT),
                                        GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
                                        NULL);
  g_object_set_data(G_OBJECT(Denemo.printarea), "offset-dialog", (gpointer)dialog);
  GtkWidget *vbox = gtk_vbox_new(FALSE, 8);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), vbox,
		      TRUE, TRUE, 0);
  gchar *text = g_strdup_printf("Current offset %d, %d\nDrag in print window to change this\nClick OK to apply the position shift to the directive", offsetx, -offsety);
  GtkWidget *label = gtk_label_new(text);
  g_free(text);
  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0);
  gtk_widget_show_all (dialog);

  gint val;

  g_signal_connect(dialog, "response", G_CALLBACK(get_drag_offset), label);
  gtk_widget_show_all(dialog);
  gtk_main();
  offsetx = (intptr_t) g_object_get_data(G_OBJECT(Denemo.printarea), "offsetx");
  offsety = (intptr_t) g_object_get_data(G_OBJECT(Denemo.printarea), "offsety");
  val =  (intptr_t)g_object_get_data(G_OBJECT(dialog), "offset-response");
  g_object_set_data(G_OBJECT(Denemo.printarea), "offset-dialog", NULL);
  gtk_widget_destroy(dialog);
  if(val == GTK_RESPONSE_ACCEPT) {
    x= scm_makfrom0str (g_strdup_printf("%.1f", offsetx/10.0));
    y= scm_makfrom0str (g_strdup_printf("%.1f", -offsety/10.0));
    ret = scm_cons(x, y);
  } else
    ret = SCM_BOOL(FALSE);//FIXME add a RESET button for which return TRUE to reset the overall offset to zero.
  return ret;
}

/* return a string representing the relative font size the user wishes to use*/
SCM scheme_get_relative_font_size(void) {
  if(Denemo.printarea==NULL)
    return SCM_BOOL(FALSE);
  gchar *value = g_object_get_data(G_OBJECT(Denemo.printarea), "font-size");
  if(value)
    g_free(value);
  value = string_dialog_entry (Denemo.gui, "Font Size", "Give a value (+/-) to adjust font size by", "0");
  if(!value)
    value = g_strdup("0");
  gchar *clean = g_strdup_printf("%d", atoi(value));
  g_free(value);
  g_object_set_data(G_OBJECT(Denemo.printarea), "font-size", (gpointer)clean);
  return scm_from_locale_stringn (clean, strlen(clean));
}
void get_clipboard(GtkAction * action, DenemoScriptParam *param);
/* return a string from the X selection */
SCM scheme_get_text_selection (void) {
  SCM ret;
  DenemoScriptParam param;
  get_clipboard(NULL, &param);
  if(param.status) {
    ret = scm_from_locale_stringn(param.string->str, param.string->len);
    g_string_free(param.string, TRUE);
  }
  else
    ret = SCM_BOOL(FALSE);
  return ret;
}






/* return a string representing the padding desired for some lilypond graphic
 or #f if no printarea or user cancels*/
SCM scheme_get_padding(void) {
  SCM pad, ret;
  if(Denemo.printarea==NULL)
    return SCM_BOOL(FALSE);
  if(g_object_get_data(G_OBJECT(Denemo.printarea), "pad-dialog")){
    warningdialog("Already in a padding dialog");
    return SCM_BOOL_F;
  }
     
  gint padding = (intptr_t)g_object_get_data(G_OBJECT(Denemo.printarea), "padding");

  GtkWidget *dialog = gtk_dialog_new_with_buttons ("Select Padding in Print Window",
                                        GTK_WINDOW (Denemo.window),
                                        (GtkDialogFlags) (GTK_DIALOG_DESTROY_WITH_PARENT),
                                        GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
                                        NULL);
  g_object_set_data(G_OBJECT(Denemo.printarea), "pad-dialog", (gpointer)dialog);
  GtkWidget *vbox = gtk_vbox_new(FALSE, 8);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), vbox,
		      TRUE, TRUE, 0);
  gchar *text = g_strdup_printf("Current padding is %d\nUse right click in print window to change this\nClick OK to apply the padding to the music item drawn by the directive", padding);
  GtkWidget *label = gtk_label_new(text);
  g_free(text);
  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0);
  gtk_widget_show_all (dialog);

  gint val;

  g_signal_connect(dialog, "response", G_CALLBACK(get_drag_pad), label);
  gtk_widget_show_all(dialog);
  gtk_main();
  padding = (intptr_t) g_object_get_data(G_OBJECT(Denemo.printarea), "padding");
  val =  (intptr_t)g_object_get_data(G_OBJECT(dialog), "pad-response");
  g_object_set_data(G_OBJECT(Denemo.printarea), "pad-dialog", NULL);
  gtk_widget_destroy(dialog);
  if(val == GTK_RESPONSE_ACCEPT) {
    ret = scm_makfrom0str (g_strdup_printf("%d", padding/10));
  } else
    ret = SCM_BOOL(FALSE);
  return ret;
}



/* create a dialog with the options & return the one chosen, of #f if
   the user cancels
*/
SCM scheme_get_option(SCM options) {
  SCM scm;
  gchar *response;
  size_t length;
  gchar *str=NULL;
  if(scm_is_string(options)){
    str = scm_to_locale_stringn(options, &length);
    response = get_option(str, length);
  }
  if(response)
    scm = scm_from_locale_stringn (response, strlen(response));
  else scm = SCM_BOOL(FALSE);
  return  scm;
}


/* Scheme interface to DenemoDirectives (formerly LilyPond directives attached to notes/chords) */
/* store the script to be invoked as an action for a directive tagged with tag */
SCM scheme_set_action_script_for_tag(SCM tag, SCM script) {
  if(scm_is_string(tag)){
    gchar *the_tag = scm_to_locale_string(tag);
    if(scm_is_string(script)){
      gchar *the_script = scm_to_locale_string(script);
      set_action_script_for_tag(the_tag, the_script);
      return SCM_BOOL(TRUE);
    }
  }
  return SCM_BOOL(FALSE);
}

#define GET_TAG_FN_DEF(what)\
 static SCM scheme_##what##_directive_get_tag(SCM tag) {\
  gchar *tagname;\
  if(!scm_is_string(tag))\
     tagname = NULL;\
  else tagname = scm_to_locale_string(tag);\
  extern gchar *what##_directive_get_tag (gchar *tagname);\
  gchar *val = (gchar*)what##_directive_get_tag (tagname);\
  if(val) return scm_from_locale_stringn (val, strlen(val));\
  return SCM_BOOL(FALSE);\
}
GET_TAG_FN_DEF(standalone);
GET_TAG_FN_DEF(chord);
GET_TAG_FN_DEF(note);
GET_TAG_FN_DEF(staff);
GET_TAG_FN_DEF(voice);
GET_TAG_FN_DEF(score);
GET_TAG_FN_DEF(clef);
GET_TAG_FN_DEF(timesig);
GET_TAG_FN_DEF(tuplet);
GET_TAG_FN_DEF(stemdirective);
GET_TAG_FN_DEF(keysig);
GET_TAG_FN_DEF(scoreheader);
GET_TAG_FN_DEF(header);
GET_TAG_FN_DEF(paper);
GET_TAG_FN_DEF(layout);
GET_TAG_FN_DEF(movementcontrol);
#undef GET_TAG_FN_DEF

#define EDIT_FN_DEF(what)\
 static SCM scheme_text_edit_##what##_directive(SCM tag) {\
  if(!scm_is_string(tag))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  extern gboolean text_edit_##what##_directive (gchar *tagname);\
  return SCM_BOOL( text_edit_##what##_directive (tagname));\
}
#define DELETE_FN_DEF(what)\
 static SCM scheme_delete_##what##_directive(SCM tag) {\
  if(!scm_is_string(tag))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  extern gboolean delete_##what##_directive (gchar *tagname);\
  return SCM_BOOL( delete_##what##_directive (tagname));\
}
#define EDIT_DELETE_FN_DEF(what)\
EDIT_FN_DEF(what)\
DELETE_FN_DEF(what)

EDIT_FN_DEF(standalone)

EDIT_DELETE_FN_DEF(note)
EDIT_DELETE_FN_DEF(chord)
EDIT_DELETE_FN_DEF(staff)
EDIT_DELETE_FN_DEF(voice)
EDIT_DELETE_FN_DEF(score)


#define GETFUNC_DEF(what, field)\
static SCM scheme_##what##_directive_get_##field(SCM tag) {\
  if(!scm_is_string(tag))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  extern gchar* what##_directive_get_##field(gchar *tagname);\
  gchar *value = (gchar*)what##_directive_get_##field(tagname);\
  if(value)\
    return scm_makfrom0str(value);\
  return SCM_BOOL(FALSE);\
}
#define PUTFUNC_DEF(what, field)\
static SCM scheme_##what##_directive_put_##field(SCM tag, SCM value) {\
  if((!scm_is_string(tag))||(!scm_is_string(value)))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  gchar *valuename = scm_to_locale_string(value);\
  extern gboolean what##_directive_put_##field (gchar *tagname, gchar *valuename);\
  return SCM_BOOL(what##_directive_put_##field (tagname, valuename));\
}



//block to clone for new GString entries in DenemoDirective
GETFUNC_DEF(note, display)
GETFUNC_DEF(chord, display)
GETFUNC_DEF(standalone, display)
GETFUNC_DEF(staff, display)
GETFUNC_DEF(voice, display)
GETFUNC_DEF(score, display)
GETFUNC_DEF(movementcontrol, display)

PUTFUNC_DEF(note, display)
PUTFUNC_DEF(chord, display)
PUTFUNC_DEF(standalone, display)
PUTFUNC_DEF(staff, display)
PUTFUNC_DEF(voice, display)
PUTFUNC_DEF(score, display)
PUTFUNC_DEF(movementcontrol, display)
// end of block to clone


GETFUNC_DEF(note, midibytes)
GETFUNC_DEF(chord, midibytes)
GETFUNC_DEF(standalone, midibytes)
GETFUNC_DEF(staff, midibytes)
GETFUNC_DEF(voice, midibytes)
GETFUNC_DEF(score, midibytes)
GETFUNC_DEF(movementcontrol, midibytes)

PUTFUNC_DEF(note, midibytes)
PUTFUNC_DEF(chord, midibytes)
PUTFUNC_DEF(standalone, midibytes)
PUTFUNC_DEF(staff, midibytes)
PUTFUNC_DEF(voice, midibytes)
PUTFUNC_DEF(score, midibytes)
PUTFUNC_DEF(movementcontrol, midibytes)



GETFUNC_DEF(note, prefix)
GETFUNC_DEF(note, postfix)
PUTFUNC_DEF(note, prefix)
     //PUTFUNC_DEF(clef, prefix)
PUTFUNC_DEF(note, postfix)

GETFUNC_DEF(score, prefix)
GETFUNC_DEF(score, postfix)
PUTFUNC_DEF(score, prefix)
PUTFUNC_DEF(score, postfix)


PUTFUNC_DEF(staff, prefix)
PUTFUNC_DEF(voice, prefix)
GETFUNC_DEF(staff, prefix)
GETFUNC_DEF(voice, prefix)

PUTFUNC_DEF(staff, postfix)
PUTFUNC_DEF(voice, postfix)
GETFUNC_DEF(staff, postfix)
GETFUNC_DEF(voice, postfix)

GETFUNC_DEF(chord, prefix)
GETFUNC_DEF(chord, postfix)
PUTFUNC_DEF(chord, prefix)
PUTFUNC_DEF(chord, postfix)

GETFUNC_DEF(standalone, prefix)
GETFUNC_DEF(standalone, postfix)
PUTFUNC_DEF(standalone, prefix)
PUTFUNC_DEF(standalone, postfix)


#define INT_PUTFUNC_DEF(what, field)\
static SCM scheme_##what##_directive_put_##field(SCM tag, SCM value) {\
  if((!scm_is_string(tag))||(!scm_integer_p(value)))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  gint valuename = scm_num2int(value, 0, 0);\
  extern  gboolean  what##_directive_put_##field (gchar *tag, gint value);\
  return SCM_BOOL(what##_directive_put_##field (tagname, valuename));\
}
#define INT_GETFUNC_DEF(what, field)\
static SCM scheme_##what##_directive_get_##field(SCM tag) {\
  if(!scm_is_string(tag))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  extern gint what##_directive_get_##field (gchar *tag);\
  return scm_int2num(what##_directive_get_##field (tagname));\
}


#define PUTGRAPHICFUNC_DEF(what)\
static SCM scheme_##what##_directive_put_graphic(SCM tag, SCM value) {\
  if((!scm_is_string(tag))||(!scm_is_string(value)))\
     return SCM_BOOL(FALSE);\
  gchar *tagname = scm_to_locale_string(tag);\
  gchar *valuename = scm_to_locale_string(value);\
  return SCM_BOOL(what##_directive_put_graphic (tagname, valuename));\
}

PUTGRAPHICFUNC_DEF(note);
PUTGRAPHICFUNC_DEF(chord);
PUTGRAPHICFUNC_DEF(standalone);
PUTGRAPHICFUNC_DEF(staff);
PUTGRAPHICFUNC_DEF(voice);
PUTGRAPHICFUNC_DEF(score);


     //block to copy for new int field in directive
INT_PUTFUNC_DEF(note, minpixels)
INT_PUTFUNC_DEF(chord, minpixels)
INT_PUTFUNC_DEF(standalone, minpixels)
INT_PUTFUNC_DEF(staff, minpixels)
INT_PUTFUNC_DEF(voice, minpixels)
INT_PUTFUNC_DEF(score, minpixels)
INT_PUTFUNC_DEF(clef, minpixels)
INT_PUTFUNC_DEF(timesig, minpixels)
INT_PUTFUNC_DEF(tuplet, minpixels)
INT_PUTFUNC_DEF(stemdirective, minpixels)
INT_PUTFUNC_DEF(keysig, minpixels)

INT_PUTFUNC_DEF(scoreheader, minpixels)
INT_PUTFUNC_DEF(header, minpixels)
INT_PUTFUNC_DEF(paper, minpixels)
INT_PUTFUNC_DEF(layout, minpixels)
INT_PUTFUNC_DEF(movementcontrol, minpixels)

INT_GETFUNC_DEF(note, minpixels)
INT_GETFUNC_DEF(chord, minpixels)
INT_GETFUNC_DEF(standalone, minpixels)
INT_GETFUNC_DEF(staff, minpixels)
INT_GETFUNC_DEF(voice, minpixels)
INT_GETFUNC_DEF(score, minpixels)
INT_GETFUNC_DEF(clef, minpixels)
INT_GETFUNC_DEF(timesig, minpixels)
INT_GETFUNC_DEF(tuplet, minpixels)
INT_GETFUNC_DEF(stemdirective, minpixels)
INT_GETFUNC_DEF(keysig, minpixels)

INT_GETFUNC_DEF(scoreheader, minpixels)
INT_GETFUNC_DEF(header, minpixels)
INT_GETFUNC_DEF(paper, minpixels)
INT_GETFUNC_DEF(layout, minpixels)
INT_GETFUNC_DEF(movementcontrol, minpixels)

     //end block to ocpy for new int field in directive






INT_PUTFUNC_DEF(note, override)
INT_PUTFUNC_DEF(chord, override)
INT_PUTFUNC_DEF(standalone, override)
INT_PUTFUNC_DEF(staff, override)
INT_PUTFUNC_DEF(voice, override)
INT_PUTFUNC_DEF(score, override)
INT_GETFUNC_DEF(note, override)
INT_GETFUNC_DEF(chord, override)
INT_GETFUNC_DEF(standalone, override)
INT_GETFUNC_DEF(staff, override)
INT_GETFUNC_DEF(voice, override)
INT_GETFUNC_DEF(score, override)






INT_PUTFUNC_DEF(note, y)
INT_PUTFUNC_DEF(chord, y)
INT_PUTFUNC_DEF(standalone, y)
INT_GETFUNC_DEF(note, y)
INT_GETFUNC_DEF(chord, y)
INT_GETFUNC_DEF(standalone, y)
INT_PUTFUNC_DEF(note, x)
INT_PUTFUNC_DEF(chord, x)
INT_PUTFUNC_DEF(standalone, x)
INT_GETFUNC_DEF(note, x)
INT_GETFUNC_DEF(chord, x)
INT_GETFUNC_DEF(standalone, x)

INT_PUTFUNC_DEF(note, ty)
INT_PUTFUNC_DEF(chord, ty)
INT_PUTFUNC_DEF(standalone, ty)
INT_GETFUNC_DEF(note, ty)
INT_GETFUNC_DEF(chord, ty)
INT_GETFUNC_DEF(standalone, ty)
INT_PUTFUNC_DEF(note, tx)
INT_PUTFUNC_DEF(chord, tx)
INT_PUTFUNC_DEF(standalone, tx)
INT_GETFUNC_DEF(note, tx)
INT_GETFUNC_DEF(chord, tx)
INT_GETFUNC_DEF(standalone, tx)

INT_PUTFUNC_DEF(note, gy)
INT_PUTFUNC_DEF(chord, gy)
INT_PUTFUNC_DEF(standalone, gy)
INT_GETFUNC_DEF(note, gy)
INT_GETFUNC_DEF(chord, gy)
INT_GETFUNC_DEF(standalone, gy)
INT_PUTFUNC_DEF(note, gx)
INT_PUTFUNC_DEF(chord, gx)
INT_PUTFUNC_DEF(standalone, gx)
INT_GETFUNC_DEF(note, gx)
INT_GETFUNC_DEF(chord, gx)
INT_GETFUNC_DEF(standalone, gx)

INT_GETFUNC_DEF(note, width)
INT_GETFUNC_DEF(chord, width)
INT_GETFUNC_DEF(standalone, width)
INT_GETFUNC_DEF(note, height)
INT_GETFUNC_DEF(chord, height)
INT_GETFUNC_DEF(standalone, height)
 
INT_GETFUNC_DEF(score, x)
INT_GETFUNC_DEF(score, y)
INT_GETFUNC_DEF(score, tx)
INT_GETFUNC_DEF(score, ty)
INT_GETFUNC_DEF(score, gx)
INT_GETFUNC_DEF(score, gy)
INT_GETFUNC_DEF(score, width)
INT_GETFUNC_DEF(score, height)

INT_PUTFUNC_DEF(score, x)
INT_PUTFUNC_DEF(score, y)
INT_PUTFUNC_DEF(score, tx)
INT_PUTFUNC_DEF(score, ty)
INT_PUTFUNC_DEF(score, gx)
INT_PUTFUNC_DEF(score, gy)



     // block to copy for new type of directive, !!minpixels is done in block to copy for new fields!!
GETFUNC_DEF(clef, prefix)
GETFUNC_DEF(clef, postfix)
GETFUNC_DEF(clef, display)
PUTFUNC_DEF(clef, prefix)
PUTFUNC_DEF(clef, postfix)
PUTFUNC_DEF(clef, display)
PUTGRAPHICFUNC_DEF(clef);

INT_PUTFUNC_DEF(clef, x)
INT_PUTFUNC_DEF(clef, y)
INT_PUTFUNC_DEF(clef, tx)
INT_PUTFUNC_DEF(clef, ty)
INT_PUTFUNC_DEF(clef, gx)
INT_PUTFUNC_DEF(clef, gy)
INT_PUTFUNC_DEF(clef, override)
INT_GETFUNC_DEF(clef, x)
INT_GETFUNC_DEF(clef, y)
INT_GETFUNC_DEF(clef, tx)
INT_GETFUNC_DEF(clef, ty)
INT_GETFUNC_DEF(clef, gx)
INT_GETFUNC_DEF(clef, gy)
INT_GETFUNC_DEF(clef, override)
INT_GETFUNC_DEF(clef, width)
INT_GETFUNC_DEF(clef, height)
EDIT_DELETE_FN_DEF(clef)
     // end block

GETFUNC_DEF(timesig, prefix)
GETFUNC_DEF(timesig, postfix)
GETFUNC_DEF(timesig, display)
PUTFUNC_DEF(timesig, prefix)
PUTFUNC_DEF(timesig, postfix)
PUTFUNC_DEF(timesig, display)
PUTGRAPHICFUNC_DEF(timesig);

INT_PUTFUNC_DEF(timesig, x)
INT_PUTFUNC_DEF(timesig, y)
INT_PUTFUNC_DEF(timesig, tx)
INT_PUTFUNC_DEF(timesig, ty)
INT_PUTFUNC_DEF(timesig, gx)
INT_PUTFUNC_DEF(timesig, gy)
INT_PUTFUNC_DEF(timesig, override)
INT_GETFUNC_DEF(timesig, x)
INT_GETFUNC_DEF(timesig, y)
INT_GETFUNC_DEF(timesig, tx)
INT_GETFUNC_DEF(timesig, ty)
INT_GETFUNC_DEF(timesig, gx)
INT_GETFUNC_DEF(timesig, gy)
INT_GETFUNC_DEF(timesig, override)
INT_GETFUNC_DEF(timesig, width)
INT_GETFUNC_DEF(timesig, height)
EDIT_DELETE_FN_DEF(timesig)

GETFUNC_DEF(tuplet, prefix)
GETFUNC_DEF(tuplet, postfix)
GETFUNC_DEF(tuplet, display)
PUTFUNC_DEF(tuplet, prefix)
PUTFUNC_DEF(tuplet, postfix)
PUTFUNC_DEF(tuplet, display)
PUTGRAPHICFUNC_DEF(tuplet);

INT_PUTFUNC_DEF(tuplet, x)
INT_PUTFUNC_DEF(tuplet, y)
INT_PUTFUNC_DEF(tuplet, tx)
INT_PUTFUNC_DEF(tuplet, ty)
INT_PUTFUNC_DEF(tuplet, gx)
INT_PUTFUNC_DEF(tuplet, gy)
INT_PUTFUNC_DEF(tuplet, override)
INT_GETFUNC_DEF(tuplet, x)
INT_GETFUNC_DEF(tuplet, y)
INT_GETFUNC_DEF(tuplet, tx)
INT_GETFUNC_DEF(tuplet, ty)
INT_GETFUNC_DEF(tuplet, gx)
INT_GETFUNC_DEF(tuplet, gy)
INT_GETFUNC_DEF(tuplet, override)
INT_GETFUNC_DEF(tuplet, width)
INT_GETFUNC_DEF(tuplet, height)
EDIT_DELETE_FN_DEF(tuplet)

GETFUNC_DEF(stemdirective, prefix)
GETFUNC_DEF(stemdirective, postfix)
GETFUNC_DEF(stemdirective, display)
PUTFUNC_DEF(stemdirective, prefix)
PUTFUNC_DEF(stemdirective, postfix)
PUTFUNC_DEF(stemdirective, display)
PUTGRAPHICFUNC_DEF(stemdirective);

INT_PUTFUNC_DEF(stemdirective, x)
INT_PUTFUNC_DEF(stemdirective, y)
INT_PUTFUNC_DEF(stemdirective, tx)
INT_PUTFUNC_DEF(stemdirective, ty)
INT_PUTFUNC_DEF(stemdirective, gx)
INT_PUTFUNC_DEF(stemdirective, gy)
INT_PUTFUNC_DEF(stemdirective, override)
INT_GETFUNC_DEF(stemdirective, x)
INT_GETFUNC_DEF(stemdirective, y)
INT_GETFUNC_DEF(stemdirective, tx)
INT_GETFUNC_DEF(stemdirective, ty)
INT_GETFUNC_DEF(stemdirective, gx)
INT_GETFUNC_DEF(stemdirective, gy)
INT_GETFUNC_DEF(stemdirective, override)
INT_GETFUNC_DEF(stemdirective, width)
INT_GETFUNC_DEF(stemdirective, height)
EDIT_DELETE_FN_DEF(stemdirective)


GETFUNC_DEF(keysig, prefix)
GETFUNC_DEF(keysig, postfix)
GETFUNC_DEF(keysig, display)
PUTFUNC_DEF(keysig, prefix)
PUTFUNC_DEF(keysig, postfix)
PUTFUNC_DEF(keysig, display)
PUTGRAPHICFUNC_DEF(keysig);

INT_PUTFUNC_DEF(keysig, x)
INT_PUTFUNC_DEF(keysig, y)
INT_PUTFUNC_DEF(keysig, tx)
INT_PUTFUNC_DEF(keysig, ty)
INT_PUTFUNC_DEF(keysig, gx)
INT_PUTFUNC_DEF(keysig, gy)
INT_PUTFUNC_DEF(keysig, override)
INT_GETFUNC_DEF(keysig, x)
INT_GETFUNC_DEF(keysig, y)
INT_GETFUNC_DEF(keysig, tx)
INT_GETFUNC_DEF(keysig, ty)
INT_GETFUNC_DEF(keysig, gx)
INT_GETFUNC_DEF(keysig, gy)
INT_GETFUNC_DEF(keysig, override)
INT_GETFUNC_DEF(keysig, width)
INT_GETFUNC_DEF(keysig, height)
EDIT_DELETE_FN_DEF(keysig)


GETFUNC_DEF(scoreheader, prefix)
GETFUNC_DEF(scoreheader, postfix)
GETFUNC_DEF(scoreheader, display)
PUTFUNC_DEF(scoreheader, prefix)
PUTFUNC_DEF(scoreheader, postfix)
PUTFUNC_DEF(scoreheader, display)
PUTGRAPHICFUNC_DEF(scoreheader);

INT_PUTFUNC_DEF(scoreheader, x)
INT_PUTFUNC_DEF(scoreheader, y)
INT_PUTFUNC_DEF(scoreheader, tx)
INT_PUTFUNC_DEF(scoreheader, ty)
INT_PUTFUNC_DEF(scoreheader, gx)
INT_PUTFUNC_DEF(scoreheader, gy)
INT_PUTFUNC_DEF(scoreheader, override)
INT_GETFUNC_DEF(scoreheader, x)
INT_GETFUNC_DEF(scoreheader, y)
INT_GETFUNC_DEF(scoreheader, tx)
INT_GETFUNC_DEF(scoreheader, ty)
INT_GETFUNC_DEF(scoreheader, gx)
INT_GETFUNC_DEF(scoreheader, gy)
INT_GETFUNC_DEF(scoreheader, override)
INT_GETFUNC_DEF(scoreheader, width)
INT_GETFUNC_DEF(scoreheader, height)
EDIT_DELETE_FN_DEF(scoreheader)


GETFUNC_DEF(header, prefix)
GETFUNC_DEF(header, postfix)
GETFUNC_DEF(header, display)
PUTFUNC_DEF(header, prefix)
PUTFUNC_DEF(header, postfix)
PUTFUNC_DEF(header, display)
PUTGRAPHICFUNC_DEF(header);

INT_PUTFUNC_DEF(header, x)
INT_PUTFUNC_DEF(header, y)
INT_PUTFUNC_DEF(header, tx)
INT_PUTFUNC_DEF(header, ty)
INT_PUTFUNC_DEF(header, gx)
INT_PUTFUNC_DEF(header, gy)
INT_PUTFUNC_DEF(header, override)
INT_GETFUNC_DEF(header, x)
INT_GETFUNC_DEF(header, y)
INT_GETFUNC_DEF(header, tx)
INT_GETFUNC_DEF(header, ty)
INT_GETFUNC_DEF(header, gx)
INT_GETFUNC_DEF(header, gy)
INT_GETFUNC_DEF(header, override)
INT_GETFUNC_DEF(header, width)
INT_GETFUNC_DEF(header, height)
EDIT_DELETE_FN_DEF(header)


GETFUNC_DEF(paper, prefix)
GETFUNC_DEF(paper, postfix)
GETFUNC_DEF(paper, display)
PUTFUNC_DEF(paper, prefix)
PUTFUNC_DEF(paper, postfix)
PUTFUNC_DEF(paper, display)
PUTGRAPHICFUNC_DEF(paper);

INT_PUTFUNC_DEF(paper, x)
INT_PUTFUNC_DEF(paper, y)
INT_PUTFUNC_DEF(paper, tx)
INT_PUTFUNC_DEF(paper, ty)
INT_PUTFUNC_DEF(paper, gx)
INT_PUTFUNC_DEF(paper, gy)
INT_PUTFUNC_DEF(paper, override)
INT_GETFUNC_DEF(paper, x)
INT_GETFUNC_DEF(paper, y)
INT_GETFUNC_DEF(paper, tx)
INT_GETFUNC_DEF(paper, ty)
INT_GETFUNC_DEF(paper, gx)
INT_GETFUNC_DEF(paper, gy)
INT_GETFUNC_DEF(paper, override)
INT_GETFUNC_DEF(paper, width)
INT_GETFUNC_DEF(paper, height)
EDIT_DELETE_FN_DEF(paper)


GETFUNC_DEF(layout, prefix)
GETFUNC_DEF(layout, postfix)
GETFUNC_DEF(layout, display)
PUTFUNC_DEF(layout, prefix)
PUTFUNC_DEF(layout, postfix)
PUTFUNC_DEF(layout, display)
PUTGRAPHICFUNC_DEF(layout);

INT_PUTFUNC_DEF(layout, x)
INT_PUTFUNC_DEF(layout, y)
INT_PUTFUNC_DEF(layout, tx)
INT_PUTFUNC_DEF(layout, ty)
INT_PUTFUNC_DEF(layout, gx)
INT_PUTFUNC_DEF(layout, gy)
INT_PUTFUNC_DEF(layout, override)
INT_GETFUNC_DEF(layout, x)
INT_GETFUNC_DEF(layout, y)
INT_GETFUNC_DEF(layout, tx)
INT_GETFUNC_DEF(layout, ty)
INT_GETFUNC_DEF(layout, gx)
INT_GETFUNC_DEF(layout, gy)
INT_GETFUNC_DEF(layout, override)
INT_GETFUNC_DEF(layout, width)
INT_GETFUNC_DEF(layout, height)
EDIT_DELETE_FN_DEF(layout)


GETFUNC_DEF(movementcontrol, prefix)
GETFUNC_DEF(movementcontrol, postfix)

PUTFUNC_DEF(movementcontrol, prefix)
PUTFUNC_DEF(movementcontrol, postfix)

PUTGRAPHICFUNC_DEF(movementcontrol);

INT_PUTFUNC_DEF(movementcontrol, x)
INT_PUTFUNC_DEF(movementcontrol, y)
INT_PUTFUNC_DEF(movementcontrol, tx)
INT_PUTFUNC_DEF(movementcontrol, ty)
INT_PUTFUNC_DEF(movementcontrol, gx)
INT_PUTFUNC_DEF(movementcontrol, gy)
INT_PUTFUNC_DEF(movementcontrol, override)
INT_GETFUNC_DEF(movementcontrol, x)
INT_GETFUNC_DEF(movementcontrol, y)
INT_GETFUNC_DEF(movementcontrol, tx)
INT_GETFUNC_DEF(movementcontrol, ty)
INT_GETFUNC_DEF(movementcontrol, gx)
INT_GETFUNC_DEF(movementcontrol, gy)
INT_GETFUNC_DEF(movementcontrol, override)
INT_GETFUNC_DEF(movementcontrol, width)
INT_GETFUNC_DEF(movementcontrol, height)
EDIT_DELETE_FN_DEF(movementcontrol)

static
SCM scheme_put_text_clipboard(SCM optional) {
  size_t length;
  char *str=NULL;
  if(scm_is_string(optional)){
    str = scm_to_locale_stringn(optional, &length);//FIXME memory leak
    GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
    gtk_clipboard_set_text (clipboard, str, length);
    return SCM_BOOL(TRUE);
  } 
  return SCM_BOOL(FALSE);
}


static
SCM scheme_get_lyric(void) {
  SCM scm;
  DenemoObject *curObj;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || (((chord *) curObj->object)->lyric==NULL))
    scm = SCM_BOOL(FALSE);
  else
    scm = scm_makfrom0str(((chord *) curObj->object)->lyric->str);
 return  scm;
}

static
SCM scheme_get_username(void) {
  return scm_makfrom0str(Denemo.prefs.username->str);
}
static
SCM scheme_get_password(void) {
  return scm_makfrom0str(Denemo.prefs.password->str);
}

static
SCM scheme_set_midi_capture(SCM setting) {
  gboolean prev;
  prev = set_midi_capture((setting != SCM_BOOL_F));
  return prev?SCM_BOOL_T:SCM_BOOL_F;
}

static
SCM scheme_get_keyboard_state(void) {
 return scm_int2num (Denemo.keyboard_state);
}
static
SCM scheme_get_recorded_midi_on_tick(void) {
  smf_track_t *track = Denemo.gui->si->recorded_midi_track;
  if(track) { 
#define MIDI_NOTEOFF		0x80
#define MIDI_NOTEON		0x90
    smf_event_t *event = smf_track_get_next_event(track);
    if(event)
      switch ( event->midi_buffer[0] & 0xF0) {
      case MIDI_NOTEON: 
	return scm_int2num(event->time_pulses);
      case MIDI_NOTEOFF:
	return scm_int2num(-event->time_pulses);
      default: 
	return SCM_BOOL_F;
      }
  }
  return SCM_BOOL_F;
}
static
SCM scheme_get_recorded_midi_note(void) {
  smf_track_t *track = Denemo.gui->si->recorded_midi_track;
  if(track) {
    smf_event_t *event = NULL;
    if(track->next_event_number>0 && (track->next_event_number<=track->events_array->len))
      event = g_ptr_array_index(track->events_array, track->next_event_number - 1);
    if(event)
      switch ( event->midi_buffer[0] & 0xF0) {
      case MIDI_NOTEON: 
      case MIDI_NOTEOFF:
	return scm_int2num(event->midi_buffer[1]);
      default: 
	return SCM_BOOL_F;
      }
  }
  return SCM_BOOL_F;
}

static
SCM scheme_rewind_recorded_midi(void) {
  smf_track_t *track = Denemo.gui->si->recorded_midi_track;
  if(track) {
    if(track->smf==NULL) {
      if( Denemo.gui->si->smf) {
	 smf_add_track( Denemo.gui->si->smf, track);
	 smf_rewind( Denemo.gui->si->smf);
      } else
	return SCM_BOOL_F;
    }
    smf_rewind(track->smf);
    return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}



static
SCM scheme_get_midi(void) {
 gint midi;
 gboolean success = intercept_midi_event(&midi);
 if(!success)
   midi = 0;/* scripts should detect this impossible value and take action */
 gchar *buf = (gchar*)&midi;
 *buf &=0xF0;//do not return channel info

 SCM scm = scm_int2num (midi);
 return  scm;
}
SCM scheme_put_rest (SCM optional_duration) {
  gint duration;
  if(scm_integer_p(optional_duration)) {
    duration = scm_num2int(optional_duration, 0, 0);
  } else {
    for(duration=0;duration<7;duration++)
      if(Denemo.gui->prevailing_rhythm == Denemo.singleton_rhythms['r'+duration])
	break;
    g_print("using duration %d\n", duration);
  }
  if( (duration<0) || (duration>7))
    return SCM_BOOL_F;

  dnm_insertchord (Denemo.gui, duration, 0, TRUE);
  displayhelper(Denemo.gui);//without this a call to d-AddVoice causes a crash as the chord length info has not been updated
  return SCM_BOOL_T;
}

static SCM scheme_get_note_for_midi_key (SCM scm) {
  gint notenum = 0, offset, enshift, octave;      
  if(scm_is_integer(scm))
      notenum = scm_num2int(scm, 0, 0);
  if(notenum>0 && notenum<256) {
    notenum2enharmonic (notenum, &offset, &enshift, &octave);
    gchar *name =  mid_c_offsettolily (offset+7*octave, enshift);
      return scm_from_locale_string(name);
  } 
  return SCM_BOOL_F;
}
//Simulates a midi event, with no capture by any calling scheme script
static SCM scheme_put_midi (SCM scm) {
  gchar buf[3];
  gint midi = scm_num2int(scm, 0, 0);

  buf[0] = midi & 0xFF;
  buf[1] = (midi>>8)&0xFF;
  buf[2] = (midi>>16)&0xFF;
  //g_print("got %x\nbreaks as %x %x %x\n", midi&0xFFFFFF, buf[0], buf[1], buf[2]);
  if(midi) {
  gboolean capture = set_midi_capture(FALSE);//Turn off any capturing
  process_midi_event(buf);
  set_midi_capture(capture);//Restore any capturing that might be on
#if 0
  pitchentry(Denemo.gui);// this ensures any note is acted on before returning
#else
  midientry();//check for more midi in, and action it if available
#endif
  } else
    process_midi_event(buf);
 return SCM_BOOL(TRUE);
}

/* outputs a midibytes string to MIDI out. Format of midibytes as in DenemoDirective->midibytes */
SCM scheme_output_midi_bytes (SCM input) {
  char *next;
  char val;
  gint i, numbytes;
  gint channel;
  gint volume;
  gint tracknumber;
  if(!scm_is_string(input))
    return SCM_BOOL_F;
  DenemoStaff *curstaffstruct = (DenemoStaff *) Denemo.gui->si->currentstaff->data;
  channel = get_midi_channel();
  volume = curstaffstruct->volume;
  DevicePort *DP = (DevicePort *) device_manager_get_DevicePort(curstaffstruct->device_port->str);
  gchar *string_input = scm_to_locale_string(input);
  gchar *bytes = substitute_midi_values(string_input, channel, volume);

  for(i=0, next=bytes;*next; next++){
    val = strtol(next, &next, 0);
    i++;
    if(*next==0)
         break;
  }

  numbytes = i;
  unsigned char *buffer = (unsigned char*) g_malloc0(numbytes);
  for(i=0, next=bytes;i<numbytes;i++, next++)
    buffer[i] = (unsigned char) strtol(next, &next, 0);
			    
  g_free(bytes); 
   
  g_debug("\nbuffer[0] = %d buffer[1] = %d buffer[2] = %d\n", buffer[0], buffer[1], buffer[2]);
  if (Denemo.prefs.midi_audio_output == Jack)
    jack_output_midi_event(buffer, 0, 0);
  else if (Denemo.prefs.midi_audio_output == Fluidsynth)
    fluid_output_midi_event(buffer);
  return  SCM_BOOL(TRUE);
}

static SCM scheme_play_midikey(SCM scm) {
    guint midi = scm_num2int(scm, 0, 0);
    gint key =  (midi>>8)&0xFF;
    gint channel = midi&0xF;
    double volume = ((midi>>16)&0xFF)/255.0;
    //g_print("Playing %x at %f volume, %d channel\n", key, (double)volume, channel);
    play_midikey(key, 0.2, volume, channel);
    //g_usleep(200000);
 return SCM_BOOL(TRUE);
}



typedef struct cb_scheme_and_id { gchar *scheme_code; gint id;} cb_scheme_and_id;

static gboolean scheme_callback_one_shot_timer(cb_scheme_and_id *scheme){
    char *scheme_code = scheme->scheme_code;
    if(scheme->id == Denemo.gui->id)
      scm_c_eval_string(scheme_code);
    else
     g_warning("Timer missed for gui %d\n", scheme->id);
    g_free(scheme);
    g_free(scheme_code);
    return FALSE; 
}

static SCM scheme_one_shot_timer(SCM duration_amount, SCM callback) {
  char *scheme_code = scm_to_locale_string(callback);	
  gint duration = scm_num2int(duration_amount, 0, 0);
  cb_scheme_and_id *scheme = g_malloc(sizeof(cb_scheme_and_id));
  scheme->scheme_code = scheme_code;
  scheme->id = Denemo.gui->id;
  g_timeout_add(duration, (GSourceFunc)scheme_callback_one_shot_timer, (gpointer) scheme); 
  return SCM_BOOL(TRUE);
}

static gboolean scheme_callback_timer(cb_scheme_and_id *scheme){
    char *scheme_code = scheme->scheme_code;
    if(scheme->id == Denemo.gui->id)
      scm_c_eval_string(scheme_code);
    else
     g_warning("Timer missed for gui %d\n", scheme->id);
   
    return TRUE; //continue to call
}


static SCM scheme_timer(SCM duration_amount, SCM callback) {
  char *scheme_code = scm_to_locale_string(callback);	
  gint duration = scm_num2int(duration_amount, 0, 0);
  cb_scheme_and_id *scheme = g_malloc(sizeof(cb_scheme_and_id));
  scheme->scheme_code = scheme_code;
  scheme->id = Denemo.gui->id;
  g_timeout_add(duration, (GSourceFunc)scheme_callback_timer, (gpointer) scheme); 
  return scm_int2num((gint)scheme);
}

static SCM scheme_kill_timer(SCM id) {
  cb_scheme_and_id *scheme = (cb_scheme_and_id *)scm_num2int(id, 0, 0);
  if(scheme) {
    g_source_remove_by_user_data(scheme);//FIXME this timer leaks the memory of the scheme code and id
    //g_print("Freeing %s\n", scheme->scheme_code);
    g_free(scheme->scheme_code);
    g_free(scheme);
    return SCM_BOOL_T;
  }
  return SCM_BOOL_F;
}




static SCM scheme_bass_figure(SCM bass, SCM harmony) {
  gint bassnum = scm_num2int(bass, 0, 0);
  gint harmonynum = scm_num2int(harmony, 0, 0);
  gchar *interval = determine_interval(bassnum, harmonynum);
  SCM ret= scm_makfrom0str(interval);
  g_free(interval);
  return ret;
}



//badly named:
static SCM scheme_put_note_name (SCM optional) {

 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
 //FIXME scm_dynwind_begin (0); etc
   char *str=NULL;
   if(scm_is_string(optional)){
     str = scm_to_locale_string(optional);
     gint mid_c_offset;
     gint enshift;
     interpret_lilypond_notename(str, &mid_c_offset, &enshift);
     //g_print("note %s gives %d and %d\n", str, mid_c_offset, enshift);
     modify_note(thechord, mid_c_offset, enshift,  find_prevailing_clef(Denemo.gui->si));
     //thenote->mid_c_offset = interpret_lilypond_notename(str);
     displayhelper(Denemo.gui);
   return SCM_BOOL(TRUE);
  }
 }
 return SCM_BOOL(FALSE);  
}

static SCM scheme_set_accidental (SCM optional) {

 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
 //FIXME scm_dynwind_begin (0); etc
   GList *g;
   for(g=thechord->notes;g;g=g->next) {
     thenote = (note*)g->data;
     if(thenote->mid_c_offset == Denemo.gui->si->cursor_y)
       break;
   }
   if(g==NULL)
     return SCM_BOOL_F;
   DenemoScore *si = Denemo.gui->si;
   char *str=NULL;
   
   if(scm_is_string(optional)) {
     str = scm_to_locale_string(optional);     
     thenote->enshift = lilypond_to_enshift(str);
   } else if(scm_is_integer(optional))
     thenote->enshift = scm_to_int(optional);
   else
     thenote->enshift = 0;
   if((thenote->enshift<-2)||(thenote->enshift>2)) 
      thenote->enshift = 0;
   showwhichaccidentals ((objnode *) si->currentmeasure->data,
			 si->curmeasurekey, si->curmeasureaccs);
   //  find_xes_in_measure (si, si->currentmeasurenum, si->cursortime1,
   //			   si->cursortime2); causes a crash, si is not passed correctly, why???
   //thenote->mid_c_offset = interpret_lilypond_notename(str);
   displayhelper(Denemo.gui);
   return SCM_BOOL(TRUE);
 }
}





//create a putnote here that takes a duration and numdots and note name, inserts a chord and calls the scheme_put_note_name above - this can be done via script at present, e.g. (d-C) (d-Change3) (d-AddDot) (d-PutNoteName "eis''")


//Puts a note into the chord at the cursor PARAM lily is a string representation of the note
static SCM scheme_insert_note_in_chord (SCM lily) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD)) 
   return SCM_BOOL(FALSE);
 
 //FIXME scm_dynwind_begin (0); etc
 char *str=NULL;
 if(scm_is_string(lily)){
   str = scm_to_locale_string(lily);
   gint mid_c_offset;
   gint enshift;
   interpret_lilypond_notename(str, &mid_c_offset, &enshift);
   
   //g_print("note %s gives %d and %d\n", str, mid_c_offset, enshift);
   addtone(curObj, mid_c_offset, enshift,  find_prevailing_clef(Denemo.gui->si));
   score_status(gui, TRUE);
   displayhelper(Denemo.gui);
   return SCM_BOOL_T;
 } 
 return SCM_BOOL(FALSE);
}


//return the number of objects in the copybuffer at staff m
static SCM scheme_get_clip_objects(SCM m) {
 gint staff = scm_num2int(m, 0, 0);
 gint num = get_clip_objs(staff);
 if(num==-1)
   return SCM_BOOL_F;
 else
   return  scm_int2num(num);
}

//return the type of the nth object in the copybuffer
static SCM scheme_get_clip_obj_type(SCM m, SCM n) {
 gint value = scm_num2int(n, 0, 0); 
 gint staff = scm_num2int(m, 0, 0);
 DenemoObjType type = get_clip_obj_type(staff, value);
 if(type==-1)
   return SCM_BOOL_F;
 else
   return  scm_int2num(type);
}


//insert the nth object from the denemo copybuffer
static SCM scheme_put_clip_obj(SCM m, SCM n) {
 gint value = scm_num2int(n, 0, 0);
 gint staff = scm_num2int(m, 0, 0);
 return SCM_BOOL(insert_clip_obj(staff, value));
}

static SCM scheme_adjust_xes (SCM optional) {
  find_xes_in_all_measures (Denemo.gui->si);
  return SCM_BOOL_T;
}

static gint flash_cursor(void) {
  gtk_widget_queue_draw (Denemo.scorearea);
  return TRUE;
}
static SCM scheme_highlight_cursor (SCM optional) {
  static gint id;
  Denemo.prefs.cursor_highlight = !Denemo.prefs.cursor_highlight;
  if(id) {
    g_source_remove(id);
    id = 0;
  } else
    if( Denemo.prefs.cursor_highlight)
      id = g_timeout_add(500, (GSourceFunc)flash_cursor, NULL);
  //g_print("Cursor highlighting %d id %d", Denemo.prefs.cursor_highlight, id);
  return SCM_BOOL_T;
}

static SCM scheme_get_type (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || !(DENEMO_OBJECT_TYPE_NAME(curObj)))
   return scm_makfrom0str("None");
 if(Denemo.gui->si->cursor_appending)
    return  scm_makfrom0str("Appending");
 return  scm_makfrom0str(DENEMO_OBJECT_TYPE_NAME(curObj));
}

static SCM scheme_get_tuplet (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=TUPOPEN))
   return SCM_BOOL_F;
 GString *ratio = g_string_new("");
 g_string_printf(ratio, "%d/%d", ((tupopen*)curObj->object)->numerator, ((tupopen*)curObj->object)->denominator);
 return  scm_makfrom0str(g_string_free(ratio, FALSE));
}

static SCM scheme_set_tuplet (SCM ratio) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=TUPOPEN))
   return SCM_BOOL_F;
 gchar *theratio = scm_to_locale_string(ratio);
 sscanf(theratio, "%d/%d", &((tupopen*)curObj->object)->numerator, &((tupopen*)curObj->object)->denominator);
 g_print("Set %d/%d\n", (((tupopen*)curObj->object)->numerator), (((tupopen*)curObj->object)->denominator));
   if(((tupopen*)curObj->object)->denominator);
   return  SCM_BOOL_T;
 ((tupopen*)curObj->object)->denominator = 1;
 return  SCM_BOOL_F;
}



static SCM scheme_get_nonprinting (SCM optional) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || curObj->isinvisible)
    return SCM_BOOL_T;
  return SCM_BOOL_F;
}

static SCM scheme_set_nonprinting (SCM optional) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) ||  (curObj->type!=CHORD))
    return SCM_BOOL_F;
  if(scm_is_bool(optional) && optional==SCM_BOOL_F)
    curObj->isinvisible = FALSE;
  else
    curObj->isinvisible = TRUE;
  return SCM_BOOL_T;
}


static SCM scheme_is_slur_start (SCM optional) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  chord *thechord;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD)  || !(thechord = (chord *)  curObj->object) || !(thechord->slur_begin_p))
    return SCM_BOOL_F;
  return SCM_BOOL_T;
}

static SCM scheme_is_slur_end (SCM optional) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  chord *thechord;
  if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD)  || !(thechord = (chord *)  curObj->object) || !(thechord->slur_end_p))
    return SCM_BOOL_F;
  return SCM_BOOL_T;
}

SCM scheme_is_in_selection (void) {
  return SCM_BOOL(in_selection(Denemo.gui->si));
}





static SCM scheme_clear_clipboard(SCM optional) {
  clearbuffer();
  return SCM_BOOL(TRUE);
}



/* shifts the note at the cursor by the number of diatonic steps passed in */
SCM scheme_diatonic_shift (SCM optional) {
 DenemoGUI *gui = Denemo.gui;
 DenemoObject *curObj;
 chord *thechord;
 note *thenote;
 if(!Denemo.gui || !(Denemo.gui->si) || !(Denemo.gui->si->currentobject) || !(curObj = Denemo.gui->si->currentobject->data) || (curObj->type!=CHORD) || !(thechord = (chord *)  curObj->object) || !(thechord->notes) || !(thenote = (note *) thechord->notes->data))
   return SCM_BOOL(FALSE);
 else {
   //FIXME scm_dynwind_begin (0); etc
   char *str=NULL;
   if(scm_is_string(optional)){
     str = scm_to_locale_string(optional);
     gint shift;
     sscanf(str, "%d", &shift);
     
     g_print("note shift %s ie %d\n", str, shift);
     modify_note(thechord, thenote->mid_c_offset+shift, gui->si->curmeasureaccs[offsettonumber(thenote->mid_c_offset+shift)],  find_prevailing_clef(Denemo.gui->si));
     //thenote->mid_c_offset = interpret_lilypond_notename(str);
     displayhelper(Denemo.gui);
   }
 }
 return SCM_BOOL(FALSE);  
}

// moves the cursor in the direction indicated, observing within_measure and if stopping stopping at empty measures

static gboolean to_object_direction(gboolean within_measure, gboolean right, gboolean stopping) {
  DenemoGUI *gui = Denemo.gui;
  if(!Denemo.gui || !(Denemo.gui->si))
    return FALSE;
  GList *start_obj = Denemo.gui->si->currentobject;
  GList *start_measure = Denemo.gui->si->currentmeasure;
  if(start_obj && Denemo.gui->si->cursor_appending)
    movecursorleft(NULL);
  if(start_obj==NULL){
    if(within_measure)
      return FALSE;
    // start object is NULL, not restricted to current measure
    if(right) {
      if(start_measure->next) {
	movetomeasureright(NULL);
	if(Denemo.gui->si->currentobject)
	  return TRUE;
	else
	  if(stopping) return FALSE;
	  else
	    return to_object_direction(within_measure, right, stopping);
      } else
	return FALSE;
    }
    // going left, start object is NULL, not restricted to current measure, going previous
    if(start_measure->prev) {
      movecursorleft(NULL);
      if(Denemo.gui->si->currentobject==NULL) 
	if(stopping) return FALSE;
	else
	  return to_object_direction(within_measure, right, stopping);
      movecursorleft(NULL);
      return TRUE;
    }
    return FALSE;
  }
  //start object is not NULL
  if(within_measure){
    if(right) {
      if(start_obj->next) {
	movecursorright(NULL);
	return TRUE;
      }
      return FALSE;
    }
    //left
    if(start_obj->prev==NULL)
      return FALSE;
  }
  //not restricted to this measure
  if(right) {
    if(start_obj->next) {
      movecursorright(NULL);
      return TRUE;}
    if(start_measure->next) {
      movetomeasureright(NULL);
      if(Denemo.gui->si->currentobject==NULL)
	if(stopping) return FALSE;
	else
	  return to_object_direction(within_measure, right, stopping);
      return TRUE;
    }
    return FALSE;
  }
  //left
  if(start_obj->prev) {
    movecursorleft(NULL);
    return TRUE;
  }
  if(start_measure->prev) {
    movecursorleft(NULL);
    if(Denemo.gui->si->currentobject==NULL)
      if(stopping) return FALSE;
      else
	return to_object_direction(within_measure, right, stopping);
    movecursorleft(NULL);
    return TRUE;
  }
  return FALSE;
}

static gboolean to_next_object(gboolean within_measure, gboolean stopping) {
 
  return to_object_direction(within_measure, TRUE, stopping);  
}
static gboolean to_prev_object(gboolean within_measure, gboolean stopping) {
 
  return to_object_direction(within_measure, FALSE, stopping);  
}
/* moves currentobject to next object by calling cursorright.
   Steps over barlines (i.e. cursor_appending).
   returns TRUE if currentobject is different after than before doing the call
*/
SCM scheme_next_object (void) {
  return SCM_BOOL(to_next_object(FALSE, FALSE));
}

/* moves currentobject to prev object by calling cursorleft.
   Steps over barlines (i.e. cursor_appending).
   returns TRUE if currentobject is different after than before doing the call
*/
SCM scheme_prev_object (void) {
return SCM_BOOL(to_prev_object(FALSE, FALSE));
}


/* moves currentobject to next object in measure, if any
   returns TRUE if currentobject is different after than before doing the call
*/
SCM scheme_next_object_in_measure (void) {
return SCM_BOOL(to_next_object(TRUE, FALSE));
}

/* moves currentobject to previous object in measure, if any
   returns TRUE if currentobject is different after than before doing the call
*/
SCM scheme_prev_object_in_measure (void) {
return SCM_BOOL(to_prev_object(TRUE, FALSE));
}


SCM scheme_refresh_display (SCM optional) {
  displayhelper(Denemo.gui);
  //done in displayhelper write_status(Denemo.gui);
  return SCM_BOOL(TRUE);
}



SCM scheme_set_saved (SCM optional) {
  //scm_is_bool(optional) &&
  if(optional == SCM_BOOL_F)
    score_status(Denemo.gui, TRUE);
  else
    score_status(Denemo.gui, FALSE);
  return SCM_BOOL(TRUE);
}

SCM scheme_get_saved (SCM optional) {
  return SCM_BOOL(!Denemo.gui->notsaved);
}

SCM scheme_mark_status (SCM optional) {
  return SCM_BOOL(mark_status());

}


/* moves currentobject to object in the selection in the direction indicated by right.
   Steps over barlines (i.e. cursor_appending).
 returns TRUE if currentobject is different after than before the call
*/
static gboolean to_selected_object_direction (gboolean right) {
  DenemoGUI *gui = Denemo.gui;
  DenemoObject *curObj;
  chord *thechord;
  note *thenote;
  if(!Denemo.gui || !(Denemo.gui->si))
    return FALSE;
  // save_selection(Denemo.gui->si);
  gboolean success = to_object_direction(FALSE, right, FALSE);
  if(!success)
    success = to_object_direction(FALSE, right, FALSE);
  // restore_selection(Denemo.gui->si);
  //g_print("success %d\n", success);
  if((success) && in_selection(Denemo.gui->si))
    return TRUE;
 if(success)
   to_object_direction(FALSE, !right, FALSE);
  return FALSE;  
}





/* moves currentobject to next object in the selection.
   Steps over barlines (i.e. cursor_appending).
 returns TRUE if currentobject is different after than before the call
*/
SCM scheme_next_selected_object (SCM optional) {
  return SCM_BOOL(to_selected_object_direction(TRUE));
}

/* moves currentobject to previous object in the selection.
   Steps over barlines (i.e. cursor_appending).
 returns TRUE if currentobject is different after than before the call
*/
SCM scheme_prev_selected_object (SCM optional) {
  return SCM_BOOL(to_selected_object_direction(FALSE));
}


static gboolean to_standalone_directive_direction (gboolean right) {
  gboolean ret = to_object_direction(FALSE, right, FALSE);
  if(!ret)
    return ret;
  if(Denemo.gui->si->currentobject && Denemo.gui->si->currentobject->data &&
    ((DenemoObject*) Denemo.gui->si->currentobject->data)->type == LILYDIRECTIVE)
    return TRUE;
  else
    return 
      to_standalone_directive_direction (right);
}


SCM scheme_next_standalone_directive (SCM optional) {
  return SCM_BOOL(to_standalone_directive_direction(TRUE));
}

SCM scheme_prev_standalone_directive (SCM optional) {
  return SCM_BOOL(to_standalone_directive_direction(FALSE));
}

static gboolean to_chord_direction (gboolean right, gboolean stopping) {
  gboolean ret = to_object_direction(FALSE, right, stopping);
  if(!ret)
    return ret;
  if(Denemo.gui->si->currentobject && Denemo.gui->si->currentobject->data &&
    ((DenemoObject*) Denemo.gui->si->currentobject->data)->type == CHORD)
    return TRUE;
  else
    return 
      to_chord_direction (right, stopping);
}






SCM scheme_next_chord (SCM optional) {
  return SCM_BOOL(to_chord_direction(TRUE, FALSE));
}

SCM scheme_prev_chord (SCM optional) {
  return SCM_BOOL(to_chord_direction(FALSE, FALSE));
}


  // there is a significant problem with the concept of next note in a chord of several notes. We have no way of iterating over the notes of a chord
  // since the notes may be altered during the iteration and Denemo does not define a "currentnote"
//This next note is next chord that is not a rest in the given direction.
static gboolean to_note_direction(gboolean right, gboolean stopping) {
  gboolean ret = to_chord_direction(right, stopping);
 if(!ret)
    return ret;
 if(Denemo.gui->si->currentobject && Denemo.gui->si->currentobject->data &&
    ((DenemoObject*) Denemo.gui->si->currentobject->data)->type == CHORD && 
    ((((chord *)(((DenemoObject*) Denemo.gui->si->currentobject->data)->object))->notes))
    && (!Denemo.gui->si->cursor_appending))
   return TRUE;
  else
    return to_note_direction (right, stopping);
}


SCM scheme_next_note (SCM optional) {
  return SCM_BOOL(to_note_direction(TRUE, FALSE));
}

SCM scheme_prev_note (SCM optional) {
  return SCM_BOOL(to_note_direction(FALSE, FALSE));
}

static void   update_scheme_snippet_ids(void) {
 DenemoGUI *gui = Denemo.gui;
 GList *g;
 gint i;
 for(g = gui->rhythms, i=1;g;g=g->next, i++) {
   RhythmPattern *r =(RhythmPattern *)g->data;
   if(r->name) {
     gchar *command = g_strdup_printf("(define Snippet::%s %d)", r->name, i);
     call_out_to_guile(command);
     g_free(command);
   }
 }
}

static SCM scheme_create_snippet_from_object (SCM name) {
  if(scm_is_string(name)){
     gchar *str = scm_to_locale_string(name);
  if(Denemo.gui->si->currentobject) {
    DenemoObject*clonedobj = dnm_clone_object( Denemo.gui->si->currentobject->data);
    RhythmPattern *r = (RhythmPattern*)g_malloc0(sizeof(RhythmPattern));
    install_button_for_pattern(r, str);
    r->clipboard = g_list_append(NULL, g_list_append(NULL, clonedobj));
    append_rhythm(r, NULL);
    RhythmElement * relement = (RhythmElement*)g_malloc0(sizeof(RhythmElement));
    relement->icon = str;
    r->name = str;
    r->rsteps = g_list_append(NULL, relement);
    r->rsteps->prev=r->rsteps->next = r->rsteps;//make list circular
    SCM ret = scm_int2num( insert_pattern_in_toolbar(r));
    update_scheme_snippet_ids();
    return ret;
  }
  }
  return SCM_BOOL_F;  
}

static SCM scheme_select_snippet (SCM number) {
  if(scm_is_integer(number)) {
     gint position = scm_num2int(number, 0, 0);
     GList *g = g_list_nth(Denemo.gui->rhythms, position-1);
     if(g) {
       RhythmPattern *r = g->data;
       if(r) {
	 
	 select_rhythm_pattern(r);
	 
	 return SCM_BOOL_T;
       }
     }
  }
  
  return SCM_BOOL_F;
}

static SCM scheme_insert_snippet (SCM number) {
  if(scm_is_integer(number)) {
     gint position = scm_num2int(number, 0, 0);
     GList *g = g_list_nth(Denemo.gui->rhythms, position-1);
     if(g) {
       RhythmPattern *r = g->data;
       if(r) {
	
	 select_rhythm_pattern( r); 
	 insert_note_following_pattern(Denemo.gui);
 
	 return SCM_BOOL_T;
       }
     }
  }
  return SCM_BOOL_F;
}


/******** advances the cursor to the next note,  stopping
 at empty measures. The cursor is left after last note if no more notes */
gboolean next_editable_note(void) {
  gboolean  ret = to_note_direction(TRUE, TRUE);
  if((!ret) && Denemo.gui->si->currentobject==NULL) {
    to_note_direction(FALSE, TRUE);
  }
  if(!ret)
    movecursorright(NULL);
  return ret;
}

SCM scheme_locate_dotdenemo (SCM optional) {
  const gchar *dotdenemo = locatedotdenemo();
  if (!dotdenemo)
    return SCM_BOOL(FALSE);
  SCM scm = scm_makfrom0str (dotdenemo);
  return scm;
}

gchar *get_midi_control_command(guchar type, guchar value) {
  gchar *command = g_strdup_printf("(MIDI-shortcut::controller %d %d)", type, value);
  SCM scm = scm_c_eval_string(command);
  g_free(command);
  if(scm_is_string(scm)) {
    return scm_to_locale_string(scm);
  }
  return NULL;
}
gchar *get_midi_pitch_bend_command(gint value) {
  gchar *command = g_strdup_printf("(MIDI-shortcut::pitchbend %d)", value);
  SCM scm = scm_c_eval_string(command);
  g_free(command);
  if(scm_is_string(scm)) {
    return scm_to_locale_string(scm);
  }
  return NULL;
}


gchar* process_command_line(int argc, char**argv);//back in main

static void define_scheme_constants(void) {
  gchar *tmp;

  gint major=0, minor=0, micro=0;
  sscanf(VERSION, "%d.%d.%d", &major, &minor, &micro);
  gchar *denemo_version = g_strdup_printf("%d_%d_%d%s", major, minor, micro,
#ifdef G_OS_WIN32
"_Win"
#else
""
#endif
);
  g_print("Version %s", denemo_version);

#define DEF_SCHEME_STR(which, what, tooltip)\
  scm_c_define(which, scm_from_locale_string(what));

#define DEF_SCHEME_CONST(which, what)\
  define_scheme_int_variable(which, what, "See documentation elsewhere");


  DEF_SCHEME_CONST("DENEMO_OVERRIDE_LILYPOND", DENEMO_OVERRIDE_LILYPOND);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_GRAPHIC", DENEMO_OVERRIDE_GRAPHIC);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_EDITOR", DENEMO_OVERRIDE_EDITOR);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_AFFIX", DENEMO_OVERRIDE_AFFIX);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_TAGEDIT", DENEMO_OVERRIDE_TAGEDIT);

  DEF_SCHEME_CONST("DENEMO_OVERRIDE_VOLUME", DENEMO_OVERRIDE_VOLUME);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_DURATION", DENEMO_OVERRIDE_DURATION);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_REPEAT", DENEMO_OVERRIDE_REPEAT);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_CHANNEL", DENEMO_OVERRIDE_CHANNEL);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_TEMPO", DENEMO_OVERRIDE_TEMPO);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_TRANSPOSITION", DENEMO_OVERRIDE_TRANSPOSITION);

  DEF_SCHEME_CONST("DENEMO_OVERRIDE_ONCE", DENEMO_OVERRIDE_ONCE);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_STEP", DENEMO_OVERRIDE_STEP);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_RAMP", DENEMO_OVERRIDE_RAMP);


  DEF_SCHEME_CONST("DENEMO_OVERRIDE_RELATIVE", DENEMO_OVERRIDE_RELATIVE);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_PERCENT", DENEMO_OVERRIDE_PERCENT);

  DEF_SCHEME_CONST("DENEMO_MIDI_MASK", DENEMO_MIDI_MASK);
  DEF_SCHEME_CONST("DENEMO_MIDI_INTERPRETATION_MASK", DENEMO_MIDI_INTERPRETATION_MASK);
  DEF_SCHEME_CONST("DENEMO_MIDI_ACTION_MASK", DENEMO_MIDI_ACTION_MASK);

  DEF_SCHEME_CONST("DENEMO_OVERRIDE_DYNAMIC", DENEMO_OVERRIDE_DYNAMIC);
  DEF_SCHEME_CONST("DENEMO_OVERRIDE_HIDDEN", DENEMO_OVERRIDE_HIDDEN);

  DEF_SCHEME_CONST("VERSION_MAJOR", major);
  DEF_SCHEME_CONST("VERSION_MINOR", minor);
  DEF_SCHEME_CONST("VERSION_MICRO", micro);

  DEF_SCHEME_STR("DENEMO_VERSION", denemo_version, "Holds the denemo version major.minor.micro");
  DEF_SCHEME_STR("DENEMO_ACTIONS_DIR", g_strdup_printf("%s%c", g_build_filename(get_data_dir(), "actions", NULL), G_DIR_SEPARATOR), "Holds location of system-wide Denemo actions directory");
  DEF_SCHEME_STR("DENEMO_LOCAL_ACTIONS_DIR", g_strdup_printf("%s%c", g_build_filename(locatedotdenemo(), "actions", NULL), G_DIR_SEPARATOR), "Holds location of Denemo actions directory beneath your home directory");
  {
    gint i;
    for(i=0;i<G_N_ELEMENTS(DenemoObjTypeNames);i++) 
      DEF_SCHEME_CONST(DenemoObjTypeNames[i], i);
  }


#undef DEF_SCHEME_STR
#undef DEF_SCHEME_CONST
}
/*
  load denemo.scm from user's .denemo 
*/
static void load_local_scheme_init(void)  {
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "denemo.scm", NULL);
  if(g_file_test(filename, G_FILE_TEST_EXISTS))
    eval_file_with_catch(filename);//scm_c_primitive_load(filename);
  g_free(filename);
}

void denemo_scheme_init(void){
  gchar *initscheme = Denemo.schemeinit;
  Denemo.gui->si->undo_guard++;
 
  if(initscheme) {

    if(g_file_test(initscheme, G_FILE_TEST_EXISTS))
      eval_file_with_catch(initscheme);//scm_c_primitive_load(initscheme);
    else
      g_warning("Cannot find your scheme initialization file %s", initscheme);
  }
  //else ?????
  if(Denemo.prefs.profile->len){
    gchar *name = g_strconcat(Denemo.prefs.profile->str, ".scm", NULL);
    gchar *filename = g_build_filename(get_data_dir (), "actions", name, NULL);
    if(g_file_test(filename, G_FILE_TEST_EXISTS))
      eval_file_with_catch(filename);
    g_free(name);
    g_free(filename);
  }

  load_local_scheme_init();
  Denemo.gui->si->undo_guard--;
}

/*
  append scheme to user's denemo.scm
*/
void append_to_local_scheme_init(gchar *scheme)  {
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "denemo.scm", NULL);
  FILE *fp = fopen(filename, "a+");
  if(fp)
    fprintf(fp, "%s", scheme);
  fclose(fp);
  g_free(filename);
}


/*
  load denemo.scm from system,

*/
static void load_scheme_init(void)  {
  Denemo.gui->si->undo_guard++;
  gchar *filename = g_build_filename(get_data_dir(), "actions", "denemo.scm", NULL);
  g_debug("System wide denemo.scm %s\n", filename);
  if(g_file_test(filename, G_FILE_TEST_EXISTS))
    eval_file_with_catch(filename);//scm_c_primitive_load(filename);
  else
    g_warning("Cannot find Denemo's scheme initialization file denemo.scm");
  g_free(filename);

  Denemo.gui->si->undo_guard--;
}

/* show the user's preferred view. Assumes all hidden on entry */
void  show_preferred_view(void) {
  if (!Denemo.prefs.playback_controls)
    activate_action("/MainMenu/ViewMenu/"TogglePlaybackControls_STRING);
  if (!Denemo.prefs.midi_in_controls)
    activate_action("/MainMenu/ViewMenu/"ToggleMidiInControls_STRING);

  if (!Denemo.prefs.quickshortcuts)
    activate_action("/MainMenu/EditMenu/Preferences/Keybindings/"QuickEdits_STRING);

  if (!Denemo.prefs.toolbar)
    activate_action("/MainMenu/ViewMenu/"ToggleToolbar_STRING);

  if (!Denemo.prefs.notation_palette)
    activate_action("/MainMenu/ViewMenu/"ToggleEntryToolbar_STRING);

  if (!Denemo.prefs.console_pane)
    activate_action("/MainMenu/ViewMenu/"ToggleConsoleView_STRING);

  if (!Denemo.prefs.lyrics_pane)
    activate_action("/MainMenu/ViewMenu/"ToggleLyricsView_STRING);


  if (!Denemo.prefs.rhythm_palette)
    activate_action("/MainMenu/ViewMenu/"ToggleRhythmToolbar_STRING);


  if (!Denemo.prefs.object_palette)
    activate_action("/MainMenu/ViewMenu/"ToggleObjectMenu_STRING);

  if (Denemo.prefs.visible_directive_buttons)
   activate_action("/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);


  if(!Denemo.prefs.modal)
    gtk_widget_hide (gtk_ui_manager_get_widget (Denemo.ui_manager, "/MainMenu/ModeMenu"));

  //these menu ones are visible on entry - FIXME is this the array of toolbars below, ending in TRUE?
  if (!Denemo.prefs.playback_controls)
    toggle_playback_controls(NULL, NULL);

  if (!Denemo.prefs.midi_in_controls)
    toggle_midi_in_controls(NULL, NULL);

  if (!Denemo.prefs.toolbar)
    toggle_toolbar(NULL, NULL);
}


/* load local init.denemo or failing that system wide template file init.denemo*/
void load_initdotdenemo(void) { 
   gchar *init_file;

   init_file = g_build_filename(locatedotdenemo (), "actions", "init.denemo", NULL);
   if(g_file_test(init_file, G_FILE_TEST_EXISTS)) {
     if(open_for_real (init_file, Denemo.gui, TRUE, REPLACE_SCORE))
       g_warning("Could not open %s\n", init_file);
   } else {
     g_free(init_file);
     init_file = g_build_filename(get_data_dir (), "actions", "init.denemo", NULL);
     if (open_for_real (init_file, Denemo.gui, TRUE, REPLACE_SCORE) == -1)
       g_warning("Denemo initialization file %s not found", init_file);
     g_free(init_file);
   }
   deleteSchemeText();
} 

/* 
 * create and populate the keymap - a register of all the Denemo commands with their shortcuts
 */
static void init_keymap(void)
{
  if(Denemo.map)
    free_keymap(Denemo.map);
  Denemo.map = allocate_keymap ();
  GtkActionGroup *action_group = Denemo.action_group;
#include "register_commands.h"
} 

static void create_scheme_identfiers(void) {

  /* test with
     (d-EditMode)
     (d-2)
     (d-PutNoteName "cis''")
  */
  
  /* create scheme functions d-<name> for all the menuitem callbacks of <name> that are not check/radio items
     The scheme functions are defined to take one optional parameter which by denemo convention will be a String type,
     not necessarily null terminated, which is then passed as a GString * to the callback routines (with the first parameter, the GtkAction*, passed as NULL.
     Note that all such actions (that may be called back by scheme directly in this fashion) are given the attribute "scm" with value 1; I do not think this is being exploited in the code at present, and is perhaps not needed.
  */
#include "scheme.h"


  INSTALL_SCM_FUNCTION ("Hides all the menus", DENEMO_SCHEME_PREFIX"HideMenus",  scheme_hide_menus);
  INSTALL_SCM_FUNCTION1 ("Takes the the name of a scripted command. Runs the script stored for that command. Scripts which invoke other scripted commands use this (implicitly?) ", DENEMO_SCHEME_PREFIX"ScriptCallback", scheme_script_callback);
			
  INSTALL_SCM_FUNCTION1 ("create a dialog with the options & return the one chosen, of #f if the user cancels", DENEMO_SCHEME_PREFIX"GetOption", scheme_get_option);
  /* test with (display (d-GetOption "this\0and\0that\0")) */
  INSTALL_SCM_FUNCTION ("Returns the text on the clipboard",DENEMO_SCHEME_PREFIX"GetTextSelection",  scheme_get_text_selection);			
  INSTALL_SCM_FUNCTION ("Returns the offset that has been set by dragging in the Print view window",DENEMO_SCHEME_PREFIX"GetOffset",  scheme_get_offset);			
  INSTALL_SCM_FUNCTION ("Returns the padding that has been set by dragging in the Print view window",DENEMO_SCHEME_PREFIX"GetPadding",  scheme_get_padding);
  INSTALL_SCM_FUNCTION ("Deprecated - gets an integer from the user via a dialog",DENEMO_SCHEME_PREFIX"GetRelativeFontSize",  scheme_get_relative_font_size);			
			/* install the scheme functions for calling extra Denemo functions created for the scripting interface */
  INSTALL_SCM_FUNCTION1 ("Takes a command name. called by a script if it requires initialization the initialization script is expected to be in init.scm in the menupath of the command passed in.", DENEMO_SCHEME_PREFIX"InitializeScript", scheme_initialize_script);
  INSTALL_SCM_FUNCTION1 (" pass in a path (from below menus) to a command script. Loads the command from .denemo or system if it can be found. It is used at startup in .denemo files like ReadingNoteNames.denemo which executes (d-LoadCommand \"MainMenu/Educational/ReadingNoteNames\") to ensure that the command it needs is in the command set.", DENEMO_SCHEME_PREFIX"LoadCommand", scheme_load_command);
  INSTALL_SCM_FUNCTION ("Returns the directory holding the user's preferences",DENEMO_SCHEME_PREFIX"LocateDotDenemo", scheme_locate_dotdenemo);
  INSTALL_SCM_FUNCTION ("Returns the name of the type of object at the cursor",DENEMO_SCHEME_PREFIX"GetType",  scheme_get_type);

  INSTALL_SCM_FUNCTION ("Returns a string numerator/denominator for a tuplet open object or #f if cursor not on a tuplet open",DENEMO_SCHEME_PREFIX"GetTuplet",  scheme_get_tuplet);
  INSTALL_SCM_FUNCTION ("Set passed string as numerator/denominator for a tuplet open at cursor",DENEMO_SCHEME_PREFIX"SetTuplet",  scheme_set_tuplet);

  INSTALL_SCM_FUNCTION2 ("Takes a staff number m and a object number n. Returns the type of object at the (m, n)th position on the Denemo Clipboard or #f if none.", DENEMO_SCHEME_PREFIX"GetClipObjType",  scheme_get_clip_obj_type);
  INSTALL_SCM_FUNCTION1 ("Takes a staff number m, Returns the number of objects in the mth staff on the Denemo Clipboard or #f if none.", DENEMO_SCHEME_PREFIX"GetClipObjects",  scheme_get_clip_objects);


  INSTALL_SCM_FUNCTION2 ("Takes a staff number m and a object number n. Inserts the (m, n)th Denemo Object from Denemo Clipboard into the staff at the cursor position", DENEMO_SCHEME_PREFIX"PutClipObj",  scheme_put_clip_obj);
  INSTALL_SCM_FUNCTION ("Clears the Denemo Music Clipboard",DENEMO_SCHEME_PREFIX"ClearClipboard",  scheme_clear_clipboard);

  INSTALL_SCM_FUNCTION ("Adjusts the horizontal (x-) positioning of notes etc after paste",DENEMO_SCHEME_PREFIX"AdjustXes",  scheme_adjust_xes);

  INSTALL_SCM_FUNCTION ("Turn highlighting of cursor off/on",DENEMO_SCHEME_PREFIX"HighlightCursor",  scheme_highlight_cursor);

  INSTALL_SCM_FUNCTION ("Returns #t if there is an object at the cursor which has any printing behavior it may have overridden",DENEMO_SCHEME_PREFIX"GetNonprinting",  scheme_get_nonprinting);

  INSTALL_SCM_FUNCTION ("Sets the Non Printing attribute of a chord (or note/rest) at the cursor. For a rest this makes a non printing rest, for a note it makes it ia pure rhythm (which will not print, but can be assigned pitch, e.g. via a MIDI keyboard. Pass in #f to unset the attribute",DENEMO_SCHEME_PREFIX"SetNonprinting",  scheme_set_nonprinting);

  INSTALL_SCM_FUNCTION ("Returns #t if there is a chord with slur starting at cursor, else #f",DENEMO_SCHEME_PREFIX"IsSlurStart",  scheme_is_slur_start);

  INSTALL_SCM_FUNCTION ("Returns #t if there is a chord with slur ending at cursor, else #f",DENEMO_SCHEME_PREFIX"IsSlurEnd",  scheme_is_slur_end);

  INSTALL_SCM_FUNCTION ("Returns #t if the cursor is in the selection area, else #f",DENEMO_SCHEME_PREFIX"IsInSelection",  scheme_is_in_selection);


  INSTALL_SCM_FUNCTION ("Shifts the cursor up or down by the integer amount passed in",DENEMO_SCHEME_PREFIX"ShiftCursor",  scheme_shift_cursor);


  INSTALL_SCM_FUNCTION ("Returns the movement number counting from 1",DENEMO_SCHEME_PREFIX"GetMovement",  scheme_get_movement);
  INSTALL_SCM_FUNCTION ("Returns the staff/voice number counting from 1",DENEMO_SCHEME_PREFIX"GetStaff",  scheme_get_staff);
  INSTALL_SCM_FUNCTION ("Returns the measure number counting from 1",DENEMO_SCHEME_PREFIX"GetMeasure",  scheme_get_measure);
  INSTALL_SCM_FUNCTION ("Returns the cursor horizontal position in current measure.\n 1 = first position in measure, n+1 is appending position where n is the number of objects in current measure",DENEMO_SCHEME_PREFIX"GetHorizontalPosition",  scheme_get_horizontal_position);

  INSTALL_SCM_FUNCTION ("Returns the note name for the line or space where the cursor is",DENEMO_SCHEME_PREFIX"GetCursorNote",  scheme_get_cursor_note);
  INSTALL_SCM_FUNCTION ("Prints out information about the object at the cursor",DENEMO_SCHEME_PREFIX"DebugObject",  scheme_debug_object);

  INSTALL_SCM_FUNCTION ("Returns the name of the (highest) note in any chord at the cursor position, or #f if none",DENEMO_SCHEME_PREFIX"GetNoteName",  scheme_get_note_name);
  INSTALL_SCM_FUNCTION ("Insert rests at the cursor to the value of the one whole measure in the key signature and return the number of rests inserted", DENEMO_SCHEME_PREFIX"PutWholeMeasureRests",  scheme_put_whole_measure_rests);
  INSTALL_SCM_FUNCTION ("returns LilyPond representation of the (highest) note at the cursor, or #f if none",DENEMO_SCHEME_PREFIX"GetNote",  scheme_get_note);
  INSTALL_SCM_FUNCTION ("Returns a space separated string of LilyPond notes for the chord at the cursor position or #f if none",DENEMO_SCHEME_PREFIX"GetNotes",  scheme_get_notes);
  INSTALL_SCM_FUNCTION ("Returns the number of dots on the note at the cursor, or #f if no note",DENEMO_SCHEME_PREFIX"GetDots", scheme_get_dots);
  INSTALL_SCM_FUNCTION ("Returns the duration in LilyPond syntax of the note at the cursor, or #f if none",DENEMO_SCHEME_PREFIX"GetNoteDuration", scheme_get_note_duration);
  INSTALL_SCM_FUNCTION ("Returns start time for the object at the cursor, or #f if it has not been calculated",DENEMO_SCHEME_PREFIX"GetOnsetTime", scheme_get_onset_time);

  INSTALL_SCM_FUNCTION1 ("Takes an integer, Sets the number of ticks (PPQN) for the object at the cursor, returns #f if none; if the object is a chord it is set undotted",DENEMO_SCHEME_PREFIX"SetDurationInTicks", scheme_set_duration_in_ticks);

  INSTALL_SCM_FUNCTION ("Returns the number of ticks (PPQN) for the object at the cursor, or #f if none",DENEMO_SCHEME_PREFIX"GetDurationInTicks", scheme_get_duration_in_ticks);
  INSTALL_SCM_FUNCTION ("Returns the number of ticks (PPQN) for the chord without dots or tuplet effects at the cursor, or #f if not a chord. The value is -ve for special durations (i.e. non-standard notes)",DENEMO_SCHEME_PREFIX"GetBaseDurationInTicks", scheme_get_base_duration_in_ticks);

  INSTALL_SCM_FUNCTION ("Returns the tick count (PPQN) for the end of the object at the cursor, or #f if none",DENEMO_SCHEME_PREFIX"GetEndTick", scheme_get_end_tick);

  INSTALL_SCM_FUNCTION ("Returns the measure number at cursor position.",DENEMO_SCHEME_PREFIX"GetMeasureNumber", scheme_get_measure_number);


  INSTALL_SCM_FUNCTION ("Takes LilyPond note name string. Moves the cursor to the line or space",DENEMO_SCHEME_PREFIX"CursorToNote", scheme_cursor_to_note);

  INSTALL_SCM_FUNCTION ("Returns the prevailing keysignature at the cursor",DENEMO_SCHEME_PREFIX"GetPrevailingKeysig", scheme_get_prevailing_keysig);
  INSTALL_SCM_FUNCTION ("Returns the prevailing clef at the cursor. Note that non-builtin clefs like drum are not handled yet.",DENEMO_SCHEME_PREFIX"GetPrevailingClef", scheme_get_prevailing_clef);
  INSTALL_SCM_FUNCTION ("Returns the prevailing duration, ie duration which will be used for the next inserted note.",DENEMO_SCHEME_PREFIX"GetPrevailingDuration", scheme_get_prevailing_duration);
 
 //more work needed, see above INSTALL_SCM_FUNCTION ("Sets the prevailing keysignature at the cursor to the string of 7 steps passed. Each step can be -1, 0 or 1",DENEMO_SCHEME_PREFIX"SetPrevailingKeysig", scheme_set_prevailing_keysig);

  INSTALL_SCM_FUNCTION ("Appends a new movement without copying staff structure.",DENEMO_SCHEME_PREFIX"AddMovement", scheme_add_movement);
 


  INSTALL_SCM_FUNCTION ("Takes a string of LilyPond note names. Replaces the notes of the chord at the cursor with these notes, preserving other attributes",DENEMO_SCHEME_PREFIX"ChangeChordNotes",  scheme_change_chord_notes);
  INSTALL_SCM_FUNCTION ("Takes a LilyPond note name, and changes the note at the cursor to that note",DENEMO_SCHEME_PREFIX"PutNoteName",  scheme_put_note_name);
  INSTALL_SCM_FUNCTION ("Takes a LilyPond note name, changes the note at the cursor to have the accidental passed in either LilyPond string or integer -2..+2. Returns #f if cursor is not on a note position.  ",DENEMO_SCHEME_PREFIX"SetAccidental",  scheme_set_accidental);

  INSTALL_SCM_FUNCTION ("Inserts a rest at the cursor; either passed in duration (note  prevailing duration not supported properly).",DENEMO_SCHEME_PREFIX"PutRest",  scheme_put_rest);



  INSTALL_SCM_FUNCTION ("Takes a LilyPond note name, and adds that note to the chord",DENEMO_SCHEME_PREFIX"InsertNoteInChord",  scheme_insert_note_in_chord);


  INSTALL_SCM_FUNCTION ("Moves the note at the cursor by the number of diatonic steps passed in",DENEMO_SCHEME_PREFIX"DiatonicShift", scheme_diatonic_shift);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the right returning #t if this was possible",DENEMO_SCHEME_PREFIX"NextObject", scheme_next_object);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the left returning #t if the cursor moved",DENEMO_SCHEME_PREFIX"PrevObject", scheme_prev_object);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the next object in the current measure, returning #f if there were no more objects to the left in the current measure",DENEMO_SCHEME_PREFIX"NextObjectInMeasure", scheme_next_object_in_measure);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the previous object in the current measure, returning #f if the cursor was on the first object",DENEMO_SCHEME_PREFIX"PrevObjectInMeasure", scheme_prev_object_in_measure);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the next object in the selection. Returns #t if the cursor moved",DENEMO_SCHEME_PREFIX"NextSelectedObject", scheme_next_selected_object);
  INSTALL_SCM_FUNCTION ("Moves the cursor to the previous object in the selection. Returns #t if the cursor moved",DENEMO_SCHEME_PREFIX"PrevSelectedObject", scheme_prev_selected_object);
  INSTALL_SCM_FUNCTION ("Moves the cursor the the next object of type CHORD in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"NextChord", scheme_next_chord);
  INSTALL_SCM_FUNCTION ("Moves the cursor the the previous object of type CHORD in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"PrevChord", scheme_prev_chord);
  INSTALL_SCM_FUNCTION ("Moves the cursor the next object of type CHORD which is not a rest in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"NextNote", scheme_next_note);
  INSTALL_SCM_FUNCTION ("Moves the cursor the previous object of type CHORD which is not a rest in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"PrevNote", scheme_prev_note);
  INSTALL_SCM_FUNCTION ("Creates a music Snippet comprising the object at the cursor Returns #f if not possible, otherwise an identifier for that snippet",DENEMO_SCHEME_PREFIX"CreateSnippetFromObject", scheme_create_snippet_from_object);

  INSTALL_SCM_FUNCTION ("Selects music Snippet from passed id Returns #f if not possible",DENEMO_SCHEME_PREFIX"SelectSnippet", scheme_select_snippet);

  INSTALL_SCM_FUNCTION ("Inserts music Snippet from passed id Returns #f if not possible",DENEMO_SCHEME_PREFIX"InsertSnippet", scheme_insert_snippet);



  INSTALL_SCM_FUNCTION ("Moves the cursor the next object that is a Denemo Directive in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"NextStandaloneDirective", scheme_next_standalone_directive);
  INSTALL_SCM_FUNCTION ("Moves the cursor the previous object that is a Denemo Directive in the current staff. Returns #f if the cursor did not move",DENEMO_SCHEME_PREFIX"PrevStandaloneDirective", scheme_prev_standalone_directive);
  INSTALL_SCM_FUNCTION ("Enforces the treatment of the note at the cursor as a chord in LilyPond",DENEMO_SCHEME_PREFIX"Chordize",  scheme_chordize);
  INSTALL_SCM_FUNCTION ("Takes xml representation of a preference and adds it to the Denemo preferences",DENEMO_SCHEME_PREFIX"SetPrefs",  scheme_set_prefs);
  INSTALL_SCM_FUNCTION ("Takes a script as a string, which will be stored. All the callbacks are called when the musical score is closed" ,DENEMO_SCHEME_PREFIX"AttachQuitCallback",  scheme_attach_quit_callback);
  INSTALL_SCM_FUNCTION ("Removes a callback from the current musical score",DENEMO_SCHEME_PREFIX"DetachQuitCallback",  scheme_detach_quit_callback);
  
  INSTALL_SCM_FUNCTION4 ("Takes 4 parameters and makes http transaction with www.denemo.org", DENEMO_SCHEME_PREFIX"HTTP", scheme_http);
  
  INSTALL_SCM_FUNCTION4 ("Move to given Movement, voice measure and object position. Takes 4 parameters integers starting from 1, use #f for no change. Returns #f if it fails", DENEMO_SCHEME_PREFIX"GoToPosition", scheme_goto_position);


  INSTALL_SCM_FUNCTION3 ("Takes three strings, title, prompt and initial value. Shows these to the user and returns the user's string.", DENEMO_SCHEME_PREFIX"GetUserInput", scheme_get_user_input);

  INSTALL_SCM_FUNCTION ("Takes a message as a string. Pops up the message for the user to take note of as a warning",DENEMO_SCHEME_PREFIX"WarningDialog", scheme_warningdialog);
  INSTALL_SCM_FUNCTION ("Takes a message as a string. Pops up the message for the user to take note of as a informative message",DENEMO_SCHEME_PREFIX"InfoDialog", scheme_infodialog);
  INSTALL_SCM_FUNCTION ("Takes a message as a string. Pops up the message inside of a pulsing progressbar",DENEMO_SCHEME_PREFIX"ProgressBar", scheme_progressbar);
  INSTALL_SCM_FUNCTION ("If running, Stops the ProgressBar.",DENEMO_SCHEME_PREFIX"ProgressBarStop", scheme_progressbar_stop);
  INSTALL_SCM_FUNCTION ("Intercepts the next keypress and returns a string containing the character. Returns #f if keyboard interception was not possible.",DENEMO_SCHEME_PREFIX"GetChar", scheme_get_char);
  INSTALL_SCM_FUNCTION ("Intercepts the next keypress and returns a string containing the name of the keypress (the shortcut name). Returns #f if keyboard interception was not possible.",DENEMO_SCHEME_PREFIX"GetKeypress", scheme_get_keypress);
  INSTALL_SCM_FUNCTION ("Returns the last keypress that successfully invoked a command ",DENEMO_SCHEME_PREFIX"GetCommandKeypress", scheme_get_command_keypress);

  INSTALL_SCM_FUNCTION ("Intercepts the next keypress and returns the name of the command invoked, before invoking the command. Returns #f if the keypress is not a shortcut for any command",DENEMO_SCHEME_PREFIX"GetCommand", scheme_get_command);
  INSTALL_SCM_FUNCTION ("Intercepts the next keyboard shortcut and returns the name of the command invoked, before invoking the command. Returns #f if the keypress(es) are not a shortcut for any command",DENEMO_SCHEME_PREFIX"GetCommandFromUser", scheme_get_command_from_user);

  INSTALL_SCM_FUNCTION2("Sets an \"action script\" on the directive of the given tag", DENEMO_SCHEME_PREFIX"SetDirectiveTagActionScript", (gpointer) scheme_set_action_script_for_tag);

#define INSTALL_GET_TAG(what)\
  INSTALL_SCM_FUNCTION1 ("Takes a optional tag. Returns that tag if a "#what" directive exists at the cursor, else returns the tag of the first such directive at the cursor, or #f if none", DENEMO_SCHEME_PREFIX"DirectiveGetForTag"  "-" #what, scheme_##what##_directive_get_tag);

  INSTALL_GET_TAG(standalone);
  INSTALL_GET_TAG(chord);
  INSTALL_GET_TAG(note);
  INSTALL_GET_TAG(staff);
  INSTALL_GET_TAG(voice);
  INSTALL_GET_TAG(score);
  INSTALL_GET_TAG(clef);
  INSTALL_GET_TAG(timesig);
  INSTALL_GET_TAG(tuplet);
  INSTALL_GET_TAG(stemdirective);
  INSTALL_GET_TAG(keysig);
  INSTALL_GET_TAG(scoreheader);
  INSTALL_GET_TAG(header);
  INSTALL_GET_TAG(paper);
  INSTALL_GET_TAG(layout);
  INSTALL_GET_TAG(movementcontrol);
#undef INSTALL_GET_TAG




#define INSTALL_EDIT(what)\
  INSTALL_SCM_FUNCTION1 ("Deletes a "#what" directive of the passed in tag. Returns #f if not deleted", DENEMO_SCHEME_PREFIX"DirectiveDelete"  "-" #what, scheme_delete_##what##_directive); \
  INSTALL_SCM_FUNCTION1 ("Takes a tag. Lets the user edit (by running the editscript named by the tag) a "#what" directive of the passed in tag. Returns #f if none", DENEMO_SCHEME_PREFIX"DirectiveTextEdit"  "-" #what, scheme_text_edit_##what##_directive);
  INSTALL_EDIT(note);
  INSTALL_EDIT(chord);
  INSTALL_EDIT(staff);
  INSTALL_EDIT(voice);
  INSTALL_EDIT(score);
 install_scm_function1 (DENEMO_SCHEME_PREFIX"DirectiveTextEdit-standalone", scheme_text_edit_standalone_directive);

#define INSTALL_PUT(what, field)\
 INSTALL_SCM_FUNCTION2 ("Writes the " #field" field (a string) of the " #what" directive with the passed int tag. Creates the directive of the given type and tag if it does not exist.",DENEMO_SCHEME_PREFIX"DirectivePut" "-" #what "-" #field, scheme_##what##_directive_put_##field);

#define INSTALL_GET(what, field)\
 INSTALL_SCM_FUNCTION1 ("Gets the value of the " #field" field (a string) of the " #what" directive with the passed tag.",DENEMO_SCHEME_PREFIX"DirectiveGet" "-" #what "-" #field, scheme_##what##_directive_get_##field);


  //block to repeat for new  directive fields 

  INSTALL_GET(standalone, minpixels);
  INSTALL_GET(chord, minpixels);
  INSTALL_GET(note, minpixels);
  INSTALL_GET(staff, minpixels);
  INSTALL_GET(voice, minpixels);
  INSTALL_GET(score, minpixels);
  INSTALL_GET(clef, minpixels);
  INSTALL_GET(timesig, minpixels);
  INSTALL_GET(tuplet, minpixels);
  INSTALL_GET(stemdirective, minpixels);
  INSTALL_GET(keysig, minpixels);

  INSTALL_GET(scoreheader, minpixels);
  INSTALL_GET(header, minpixels);
  INSTALL_GET(paper, minpixels);
  INSTALL_GET(layout, minpixels);
  INSTALL_GET(movementcontrol, minpixels);

  INSTALL_PUT(standalone, minpixels);
  INSTALL_PUT(chord, minpixels);
  INSTALL_PUT(note, minpixels);
  INSTALL_PUT(staff, minpixels);
  INSTALL_PUT(voice, minpixels);
  INSTALL_PUT(score, minpixels);
  INSTALL_PUT(clef, minpixels);
  INSTALL_PUT(timesig, minpixels);
  INSTALL_PUT(tuplet, minpixels);
  INSTALL_PUT(stemdirective, minpixels);
  INSTALL_PUT(keysig, minpixels);


  INSTALL_PUT(scoreheader, minpixels);
  INSTALL_PUT(header, minpixels);
  INSTALL_PUT(paper, minpixels);
  INSTALL_PUT(layout, minpixels);
  INSTALL_PUT(movementcontrol, minpixels);

  //end block to repeat for new  directive fields 


  INSTALL_GET(standalone, midibytes);
  INSTALL_GET(chord, midibytes);
  INSTALL_GET(note, midibytes);
  INSTALL_GET(staff, midibytes);
  INSTALL_GET(voice, midibytes);
  INSTALL_GET(score, midibytes);
  INSTALL_GET(movementcontrol, midibytes);
  INSTALL_PUT(standalone, midibytes);
  INSTALL_PUT(chord, midibytes);
  INSTALL_PUT(note, midibytes);
  INSTALL_PUT(staff, midibytes);
  INSTALL_PUT(voice, midibytes);
  INSTALL_PUT(score, midibytes);
  INSTALL_PUT(movementcontrol, midibytes);





  INSTALL_GET(standalone, override);
  INSTALL_GET(chord, override);
  INSTALL_GET(note, override);
  INSTALL_GET(staff, override);
  INSTALL_GET(voice, override);
  INSTALL_GET(score, override);

  INSTALL_PUT(standalone, override);
  INSTALL_PUT(chord, override);
  INSTALL_PUT(note, override);
  INSTALL_PUT(staff, override);
  INSTALL_PUT(voice, override);
  INSTALL_PUT(score, override);


  //graphic 
  INSTALL_PUT(note, graphic);
  //INSTALL_GET(note, graphic);

  INSTALL_PUT(chord, graphic);
  //INSTALL_GET(chord, graphic);

  INSTALL_PUT(standalone, graphic);
  //INSTALL_GET(standalone, graphic);


  INSTALL_PUT(staff, graphic);
  INSTALL_PUT(voice, graphic);

  INSTALL_PUT(score, graphic);
  //graphic



  INSTALL_PUT(chord, display);
  INSTALL_PUT(chord, prefix);
  INSTALL_PUT(chord, postfix);

  INSTALL_GET(chord, display);
  INSTALL_GET(chord, prefix);
  INSTALL_GET(chord, postfix);


  INSTALL_PUT(note, display);
  INSTALL_PUT(note, prefix);
  INSTALL_PUT(note, postfix);

  INSTALL_GET(note, display);
  INSTALL_GET(note, prefix);
  INSTALL_GET(note, postfix);

  INSTALL_PUT(standalone, display);
  INSTALL_PUT(standalone, prefix);
  INSTALL_PUT(standalone, postfix);

  INSTALL_GET(standalone, display);
  INSTALL_GET(standalone, prefix);
  INSTALL_GET(standalone, postfix);


  INSTALL_PUT(staff, display);
  INSTALL_PUT(staff, prefix);
  INSTALL_PUT(staff, postfix);

  INSTALL_GET(staff, display);
  INSTALL_GET(staff, prefix);
  INSTALL_GET(staff, postfix);

  INSTALL_PUT(voice, display);
  INSTALL_PUT(voice, prefix);
  INSTALL_PUT(voice, postfix);

  INSTALL_GET(voice, display);
  INSTALL_GET(voice, prefix);
  INSTALL_GET(voice, postfix);

  INSTALL_PUT(score, display);
  INSTALL_PUT(score, prefix);
  INSTALL_PUT(score, postfix);

  INSTALL_GET(score, display);
  INSTALL_GET(score, prefix);
  INSTALL_GET(score, postfix);


INSTALL_GET(score, width);
INSTALL_GET(score, height);



INSTALL_GET(score, x);
INSTALL_GET(score, gx);
INSTALL_GET(score, tx);
INSTALL_PUT(score, x);
INSTALL_PUT(score, gx);
INSTALL_PUT(score, tx);

INSTALL_GET(score, y);
INSTALL_GET(score, gy);
INSTALL_GET(score, ty);
INSTALL_PUT(score, y);
INSTALL_PUT(score, gy);
INSTALL_PUT(score, ty);




  INSTALL_PUT(note, x);
  INSTALL_GET(note, x);
  INSTALL_PUT(chord, x);
  INSTALL_GET(chord, x);
  INSTALL_PUT(note, y);
  INSTALL_GET(note, y);
  INSTALL_PUT(chord, y);
  INSTALL_GET(chord, y);

  INSTALL_PUT(note, tx);
  INSTALL_GET(note, tx);
  INSTALL_PUT(chord, tx);
  INSTALL_GET(chord, tx);
  INSTALL_PUT(note, ty);
  INSTALL_GET(note, ty);
  INSTALL_PUT(chord, ty);
  INSTALL_GET(chord, ty);



  INSTALL_PUT(note, gx);
  INSTALL_GET(note, gx);
  INSTALL_PUT(chord, gx);
  INSTALL_GET(chord, gx);
  INSTALL_PUT(note, gy);
  INSTALL_GET(note, gy);
  INSTALL_PUT(chord, gy);
  INSTALL_GET(chord, gy);


  INSTALL_PUT(standalone, x);
  INSTALL_GET(standalone, x);
  INSTALL_PUT(standalone, y);
  INSTALL_GET(standalone, y);

  INSTALL_PUT(standalone, tx);
  INSTALL_GET(standalone, tx);
  INSTALL_PUT(standalone, ty);
  INSTALL_GET(standalone, ty);

  INSTALL_PUT(standalone, gx);
  INSTALL_GET(standalone, gx);
  INSTALL_PUT(standalone, gy);
  INSTALL_GET(standalone, gy);




  INSTALL_GET(note, width);
  INSTALL_GET(chord, width);
  INSTALL_GET(standalone, width);
  INSTALL_GET(note, height);
  INSTALL_GET(chord, height);
  INSTALL_GET(standalone, height);



     //block to copy for new type of directive
INSTALL_PUT(clef, display);
INSTALL_PUT(clef, prefix);
INSTALL_PUT(clef, postfix);
INSTALL_PUT(clef, graphic);


INSTALL_GET(clef, display);
INSTALL_GET(clef, prefix);
INSTALL_GET(clef, postfix);

INSTALL_PUT(clef, x)
INSTALL_PUT(clef, y)
INSTALL_PUT(clef, tx)
INSTALL_PUT(clef, ty)
INSTALL_PUT(clef, gx)
INSTALL_PUT(clef, gy)
INSTALL_PUT(clef, override)


INSTALL_GET(clef, x)
INSTALL_GET(clef, y)
INSTALL_GET(clef, tx)
INSTALL_GET(clef, ty)
INSTALL_GET(clef, gx)
INSTALL_GET(clef, gy)
INSTALL_GET(clef, override)
INSTALL_GET(clef, width)
INSTALL_GET(clef, height)

INSTALL_EDIT(clef);
     // end of block to copy for new type of directive

INSTALL_PUT(timesig, display);
INSTALL_PUT(timesig, prefix);
INSTALL_PUT(timesig, postfix);
INSTALL_PUT(timesig, graphic);


INSTALL_GET(timesig, display);
INSTALL_GET(timesig, prefix);
INSTALL_GET(timesig, postfix);

INSTALL_PUT(timesig, x)
INSTALL_PUT(timesig, y)
INSTALL_PUT(timesig, tx)
INSTALL_PUT(timesig, ty)
INSTALL_PUT(timesig, gx)
INSTALL_PUT(timesig, gy)
INSTALL_PUT(timesig, override)


INSTALL_GET(timesig, x)
INSTALL_GET(timesig, y)
INSTALL_GET(timesig, tx)
INSTALL_GET(timesig, ty)
INSTALL_GET(timesig, gx)
INSTALL_GET(timesig, gy)
INSTALL_GET(timesig, override)
INSTALL_GET(timesig, width)
INSTALL_GET(timesig, height)

INSTALL_EDIT(timesig);

INSTALL_PUT(tuplet, display);
INSTALL_PUT(tuplet, prefix);
INSTALL_PUT(tuplet, postfix);
INSTALL_PUT(tuplet, graphic);


INSTALL_GET(tuplet, display);
INSTALL_GET(tuplet, prefix);
INSTALL_GET(tuplet, postfix);

INSTALL_PUT(tuplet, x)
INSTALL_PUT(tuplet, y)
INSTALL_PUT(tuplet, tx)
INSTALL_PUT(tuplet, ty)
INSTALL_PUT(tuplet, gx)
INSTALL_PUT(tuplet, gy)
INSTALL_PUT(tuplet, override)


INSTALL_GET(tuplet, x)
INSTALL_GET(tuplet, y)
INSTALL_GET(tuplet, tx)
INSTALL_GET(tuplet, ty)
INSTALL_GET(tuplet, gx)
INSTALL_GET(tuplet, gy)
INSTALL_GET(tuplet, override)
INSTALL_GET(tuplet, width)
INSTALL_GET(tuplet, height)

INSTALL_EDIT(tuplet);

INSTALL_PUT(stemdirective, display);
INSTALL_PUT(stemdirective, prefix);
INSTALL_PUT(stemdirective, postfix);
INSTALL_PUT(stemdirective, graphic);


INSTALL_GET(stemdirective, display);
INSTALL_GET(stemdirective, prefix);
INSTALL_GET(stemdirective, postfix);

INSTALL_PUT(stemdirective, x)
INSTALL_PUT(stemdirective, y)
INSTALL_PUT(stemdirective, tx)
INSTALL_PUT(stemdirective, ty)
INSTALL_PUT(stemdirective, gx)
INSTALL_PUT(stemdirective, gy)
INSTALL_PUT(stemdirective, override)


INSTALL_GET(stemdirective, x)
INSTALL_GET(stemdirective, y)
INSTALL_GET(stemdirective, tx)
INSTALL_GET(stemdirective, ty)
INSTALL_GET(stemdirective, gx)
INSTALL_GET(stemdirective, gy)
INSTALL_GET(stemdirective, override)
INSTALL_GET(stemdirective, width)
INSTALL_GET(stemdirective, height)

INSTALL_EDIT(stemdirective);

INSTALL_PUT(keysig, display);
INSTALL_PUT(keysig, prefix);
INSTALL_PUT(keysig, postfix);
INSTALL_PUT(keysig, graphic);


INSTALL_GET(keysig, display);
INSTALL_GET(keysig, prefix);
INSTALL_GET(keysig, postfix);

INSTALL_PUT(keysig, x)
INSTALL_PUT(keysig, y)
INSTALL_PUT(keysig, tx)
INSTALL_PUT(keysig, ty)
INSTALL_PUT(keysig, gx)
INSTALL_PUT(keysig, gy)
INSTALL_PUT(keysig, override)


INSTALL_GET(keysig, x)
INSTALL_GET(keysig, y)
INSTALL_GET(keysig, tx)
INSTALL_GET(keysig, ty)
INSTALL_GET(keysig, gx)
INSTALL_GET(keysig, gy)
INSTALL_GET(keysig, override)
INSTALL_GET(keysig, width)
INSTALL_GET(keysig, height)

INSTALL_EDIT(keysig);


INSTALL_PUT(scoreheader, display);
INSTALL_PUT(scoreheader, prefix);
INSTALL_PUT(scoreheader, postfix);
INSTALL_PUT(scoreheader, graphic);


INSTALL_GET(scoreheader, display);
INSTALL_GET(scoreheader, prefix);
INSTALL_GET(scoreheader, postfix);

INSTALL_PUT(scoreheader, x)
INSTALL_PUT(scoreheader, y)
INSTALL_PUT(scoreheader, tx)
INSTALL_PUT(scoreheader, ty)
INSTALL_PUT(scoreheader, gx)
INSTALL_PUT(scoreheader, gy)
INSTALL_PUT(scoreheader, override)


INSTALL_GET(scoreheader, x)
INSTALL_GET(scoreheader, y)
INSTALL_GET(scoreheader, tx)
INSTALL_GET(scoreheader, ty)
INSTALL_GET(scoreheader, gx)
INSTALL_GET(scoreheader, gy)
INSTALL_GET(scoreheader, override)
INSTALL_GET(scoreheader, width)
INSTALL_GET(scoreheader, height)

INSTALL_EDIT(scoreheader);


INSTALL_PUT(header, display);
INSTALL_PUT(header, prefix);
INSTALL_PUT(header, postfix);
INSTALL_PUT(header, graphic);


INSTALL_GET(header, display);
INSTALL_GET(header, prefix);
INSTALL_GET(header, postfix);

INSTALL_PUT(header, x)
INSTALL_PUT(header, y)
INSTALL_PUT(header, tx)
INSTALL_PUT(header, ty)
INSTALL_PUT(header, gx)
INSTALL_PUT(header, gy)
INSTALL_PUT(header, override)


INSTALL_GET(header, x)
INSTALL_GET(header, y)
INSTALL_GET(header, tx)
INSTALL_GET(header, ty)
INSTALL_GET(header, gx)
INSTALL_GET(header, gy)
INSTALL_GET(header, override)
INSTALL_GET(header, width)
INSTALL_GET(header, height)

INSTALL_EDIT(header);


INSTALL_PUT(paper, display);
INSTALL_PUT(paper, prefix);
INSTALL_PUT(paper, postfix);
INSTALL_PUT(paper, graphic);


INSTALL_GET(paper, display);
INSTALL_GET(paper, prefix);
INSTALL_GET(paper, postfix);

INSTALL_PUT(paper, x)
INSTALL_PUT(paper, y)
INSTALL_PUT(paper, tx)
INSTALL_PUT(paper, ty)
INSTALL_PUT(paper, gx)
INSTALL_PUT(paper, gy)
INSTALL_PUT(paper, override)


INSTALL_GET(paper, x)
INSTALL_GET(paper, y)
INSTALL_GET(paper, tx)
INSTALL_GET(paper, ty)
INSTALL_GET(paper, gx)
INSTALL_GET(paper, gy)
INSTALL_GET(paper, override)
INSTALL_GET(paper, width)
INSTALL_GET(paper, height)

INSTALL_EDIT(paper);


INSTALL_PUT(layout, display);
INSTALL_PUT(layout, prefix);
INSTALL_PUT(layout, postfix);
INSTALL_PUT(layout, graphic);


INSTALL_GET(layout, display);
INSTALL_GET(layout, prefix);
INSTALL_GET(layout, postfix);

INSTALL_PUT(layout, x)
INSTALL_PUT(layout, y)
INSTALL_PUT(layout, tx)
INSTALL_PUT(layout, ty)
INSTALL_PUT(layout, gx)
INSTALL_PUT(layout, gy)
INSTALL_PUT(layout, override)


INSTALL_GET(layout, x)
INSTALL_GET(layout, y)
INSTALL_GET(layout, tx)
INSTALL_GET(layout, ty)
INSTALL_GET(layout, gx)
INSTALL_GET(layout, gy)
INSTALL_GET(layout, override)
INSTALL_GET(layout, width)
INSTALL_GET(layout, height)

INSTALL_EDIT(layout);

INSTALL_PUT(movementcontrol, display);
INSTALL_PUT(movementcontrol, prefix);
INSTALL_PUT(movementcontrol, postfix);
INSTALL_PUT(movementcontrol, graphic);


INSTALL_GET(movementcontrol, display);
INSTALL_GET(movementcontrol, prefix);
INSTALL_GET(movementcontrol, postfix);

INSTALL_PUT(movementcontrol, x)
INSTALL_PUT(movementcontrol, y)
INSTALL_PUT(movementcontrol, tx)
INSTALL_PUT(movementcontrol, ty)
INSTALL_PUT(movementcontrol, gx)
INSTALL_PUT(movementcontrol, gy)
INSTALL_PUT(movementcontrol, override)

  
INSTALL_GET(movementcontrol, x)
INSTALL_GET(movementcontrol, y)
INSTALL_GET(movementcontrol, tx)
INSTALL_GET(movementcontrol, ty)
  
INSTALL_GET(movementcontrol, gx)
INSTALL_GET(movementcontrol, gy)
INSTALL_GET(movementcontrol, override)
  
INSTALL_GET(movementcontrol, width)
  
INSTALL_GET(movementcontrol, height)
  
INSTALL_EDIT(movementcontrol);


#undef INSTALL_EDIT
#undef EDIT_DELETE_FN_DEF
#undef INSTALL_PUT
#undef INSTALL_GET
#undef GETFUNC_DEF
#undef PUTFUNC_DEF

#undef INT_PUTFUNC_DEF
#undef INT_GETFUNC_DEF
#undef PUTGRAPHICFUNC_DEF




  /* test with (display (d-DirectivePut-note-display "LHfinger" "test")) after attaching a LH finger directive */
  /* test with (display (d-DirectivePut-note-minpixels "LHfinger" 80)) after attaching a LH finger directive */
  /* test with (display (d-DirectiveGet-note-minpixels "LHfinger")) after attaching a LH finger directive */

  /* test with (display (d-DirectiveGet-note-display "LHfinger")) after attaching a LH finger directive */
  install_scm_function1 (DENEMO_SCHEME_PREFIX"PutTextClipboard", scheme_put_text_clipboard);
  INSTALL_SCM_FUNCTION ("Returns the lyric for the note at the cursor",DENEMO_SCHEME_PREFIX"GetLyric", scheme_get_lyric);

  INSTALL_SCM_FUNCTION ("Asks the user for a user name which is returned",DENEMO_SCHEME_PREFIX"GetUserName", scheme_get_username);
  INSTALL_SCM_FUNCTION ("Asks the user for a password which is returned",DENEMO_SCHEME_PREFIX"GetPassword", scheme_get_password);

  INSTALL_SCM_FUNCTION ("Returns an integer value, a set of bitfields representing the keyboard state, e.g. GDK_SHIFT_MASK etc",DENEMO_SCHEME_PREFIX"GetKeyboardState", scheme_get_keyboard_state);

  INSTALL_SCM_FUNCTION ("Returns the ticks of the next event on the recorded MIDI track -ve if it is a NOTEOFF or #f if none. Advances to the next note.", DENEMO_SCHEME_PREFIX"GetRecordedMidiOnTick", scheme_get_recorded_midi_on_tick);

  INSTALL_SCM_FUNCTION ("Returns the LilyPond representation of the passed MIDI key number, using the current enharmonic set.", DENEMO_SCHEME_PREFIX"GetNoteForMidiKey", scheme_get_note_for_midi_key);



  INSTALL_SCM_FUNCTION ("Returns the ticks of the next event on the recorded MIDI track -ve if it is a NOTEOFF or #f if none", DENEMO_SCHEME_PREFIX"GetRecordedMidiNote", scheme_get_recorded_midi_note);

  INSTALL_SCM_FUNCTION ("Rewinds the recorded MIDI track returns #f if no MIDI track recorded", DENEMO_SCHEME_PREFIX"RewindRecordedMidi", scheme_rewind_recorded_midi);

  INSTALL_SCM_FUNCTION ("Intercepts a MIDI event and returns it as a 4 byte number",DENEMO_SCHEME_PREFIX"GetMidi", scheme_get_midi);

  INSTALL_SCM_FUNCTION ("Takes one bool parameter - MIDI events will be captured/not captured depending on the value passed in, returns previous value.",DENEMO_SCHEME_PREFIX"SetMidiCapture", scheme_set_midi_capture);


  install_scm_function1 (DENEMO_SCHEME_PREFIX"PutMidi", scheme_put_midi);
  install_scm_function1 (DENEMO_SCHEME_PREFIX"OutputMidiBytes", scheme_output_midi_bytes);
  install_scm_function1 (DENEMO_SCHEME_PREFIX"PlayMidiKey", scheme_play_midikey);

  INSTALL_SCM_FUNCTION1 ("Takes duration and executable scheme script. Executes the passed scheme code after the passed duration milliseconds", DENEMO_SCHEME_PREFIX"OneShotTimer", scheme_one_shot_timer);
  INSTALL_SCM_FUNCTION1 ("Takes a duration and scheme script, starts a timer that tries to execute the script after every duration ms. It returns a timer id which must be passed back to destroy the timer", DENEMO_SCHEME_PREFIX"Timer", scheme_timer);
  INSTALL_SCM_FUNCTION ("Takes a timer id and destroys the timer",DENEMO_SCHEME_PREFIX"KillTimer", scheme_kill_timer);
  INSTALL_SCM_FUNCTION2 ("Returns a string for the bass figure for the two MIDI keys passed in", DENEMO_SCHEME_PREFIX"BassFigure", scheme_bass_figure);
  INSTALL_SCM_FUNCTION ("Gets the MIDI key number for the note-position where the cursor is",DENEMO_SCHEME_PREFIX"GetCursorNoteAsMidi", scheme_get_cursor_note_as_midi);
  INSTALL_SCM_FUNCTION ("Returns the MIDI key number for the note at the cursor, or 0 if none",DENEMO_SCHEME_PREFIX"GetNoteAsMidi", scheme_get_note_as_midi);
  INSTALL_SCM_FUNCTION ("Re-draws the Denemo display, which can have side effects on the data",DENEMO_SCHEME_PREFIX"RefreshDisplay", scheme_refresh_display);
  INSTALL_SCM_FUNCTION ("Sets the status of the current musical score to saved, or unsaved if passed #f",DENEMO_SCHEME_PREFIX"SetSaved", scheme_set_saved);
  INSTALL_SCM_FUNCTION ("Gets the saved status of the current musical score",DENEMO_SCHEME_PREFIX"GetSaved", scheme_get_saved);
  INSTALL_SCM_FUNCTION ("Returns #f if mark is not set",DENEMO_SCHEME_PREFIX"MarkStatus", scheme_mark_status);
  INSTALL_SCM_FUNCTION ("Takes a command name and returns the tooltip or #f if none",DENEMO_SCHEME_PREFIX"GetHelp", scheme_get_help);

  INSTALL_SCM_FUNCTION ("Takes a file name, loads keybindings from actions/menus returns #f if it fails",DENEMO_SCHEME_PREFIX"LoadKeybindings", scheme_load_keybindings);

  INSTALL_SCM_FUNCTION ("Takes a file name, saves keybindings from actions/menus returns #f if it fails",DENEMO_SCHEME_PREFIX"SaveKeybindings", scheme_save_keybindings);

  INSTALL_SCM_FUNCTION ("Clears all keybindings returns #t",DENEMO_SCHEME_PREFIX"ClearKeybindings", scheme_clear_keybindings);

  INSTALL_SCM_FUNCTION ("Takes a file name for xml format commandset, loads commands, returns #f if it fails",DENEMO_SCHEME_PREFIX"LoadCommandset", scheme_load_commandset);

  INSTALL_SCM_FUNCTION ("Takes a double or string and scales the display; return #f for invalid value else the value set. With no parameter returns the current value. ", DENEMO_SCHEME_PREFIX"Zoom", scheme_zoom);

  INSTALL_SCM_FUNCTION ("Takes a double or string and scales the tempo; returns the tempo set. With no parameter returns the current master tempo ", DENEMO_SCHEME_PREFIX"MasterTempo", scheme_master_tempo);

  INSTALL_SCM_FUNCTION ("Takes an integer or string number of beats (quarter notes) per minute as the tempo for the current movement; returns the tempo set ", DENEMO_SCHEME_PREFIX"MovementTempo", scheme_movement_tempo);


  INSTALL_SCM_FUNCTION ("Takes a double or string and scales the volume; returns the volume set ", DENEMO_SCHEME_PREFIX"MasterVolume", scheme_master_volume);

  INSTALL_SCM_FUNCTION ("Takes a integer sets the enharmonic range to use 0 = E-flat to G-sharp ", DENEMO_SCHEME_PREFIX"SetEnharmonicPosition", scheme_set_enharmonic_position);


  INSTALL_SCM_FUNCTION ("Return a string of tuning bytes (offsets from 64) for MIDI tuning message", DENEMO_SCHEME_PREFIX"GetMidiTuning", scheme_get_midi_tuning);
  INSTALL_SCM_FUNCTION ("Return name of flattest degree of current temperament", DENEMO_SCHEME_PREFIX"GetFlattest", scheme_get_flattest);

  INSTALL_SCM_FUNCTION ("Return name of sharpest degree of current temperament", DENEMO_SCHEME_PREFIX"GetSharpest", scheme_get_sharpest);
   INSTALL_SCM_FUNCTION ("Return name of current temperament", DENEMO_SCHEME_PREFIX"GetTemperament", scheme_get_temperament);
 



  INSTALL_SCM_FUNCTION ("Return a number, the midi time in seconds for the start of the object at the cursor; return #f if none ", DENEMO_SCHEME_PREFIX"GetMidiOnTime", scheme_get_midi_on_time);
  INSTALL_SCM_FUNCTION ("Return a number, the midi time in seconds for the end of the object at the cursor; return #f if none ", DENEMO_SCHEME_PREFIX"GetMidiOffTime", scheme_get_midi_off_time);

  INSTALL_SCM_FUNCTION2 ("Set start and/or end time for playback to the passed numbers/strings in seconds. Use #t if a value is not to be changed. Returns #f for bad parameters ", DENEMO_SCHEME_PREFIX"SetPlaybackInterval", scheme_set_playback_interval);

  INSTALL_SCM_FUNCTION ("Adjust start time for playback by passed number of seconds. Returns #f for bad parameter ", DENEMO_SCHEME_PREFIX"AdjustPlaybackStart", scheme_adjust_playback_start);

  INSTALL_SCM_FUNCTION ("Adjust end time for playback by passed number of seconds. Returns #f for bad parameter ", DENEMO_SCHEME_PREFIX"AdjustPlaybackEnd", scheme_adjust_playback_end);



  INSTALL_SCM_FUNCTION ("Pushes the Denemo clipboard (cut/copy buffer) onto a stack; Use d-PopClipboard to retrieve it.", DENEMO_SCHEME_PREFIX"PushClipboard", scheme_push_clipboard);

  INSTALL_SCM_FUNCTION ("Pops the Denemo clipboard (cut/copy buffer) from a stack created by d-PushClipboard. Returs #f if nothing on stack, else #t.", DENEMO_SCHEME_PREFIX"PopClipboard", scheme_pop_clipboard);

  INSTALL_SCM_FUNCTION ("Deletes all objects in the selection Returns #f if no selection else #t.", DENEMO_SCHEME_PREFIX"DeleteSelection", scheme_delete_selection);

  INSTALL_SCM_FUNCTION ("Snapshots the current movement putting it in the undo queue returns #f if no snapshot was taken because of a guard", DENEMO_SCHEME_PREFIX"TakeSnapshot", scheme_take_snapshot);

  INSTALL_SCM_FUNCTION ("Stop collecting undo information. Call DecreaseGuard when finished. Returns #f if already guarded, #t if this call is stopping the undo collection", DENEMO_SCHEME_PREFIX"IncreaseGuard", scheme_increase_guard);

  INSTALL_SCM_FUNCTION ("Drop one guard against collecting undo information. Returns #t if there are no more guards \n(undo information will be collected) \nor #f if there are still guards in place.", DENEMO_SCHEME_PREFIX"DecreaseGuard", scheme_decrease_guard);

  INSTALL_SCM_FUNCTION ("Undoes the actions performed by the script so far, starts another undo stage for the subsequent actions of the script. Note this command has the same name as the built-in Undo command, to override it when called from a script. Returns #t", DENEMO_SCHEME_PREFIX"Undo"/*sic*/, scheme_undo);
   INSTALL_SCM_FUNCTION ("Creates a new tab. Note this command has the same name as the built-in NewWindow command, to override it when called from a script. Returns #t", DENEMO_SCHEME_PREFIX"NewWindow"/*sic*/, scheme_new_window);
  
INSTALL_SCM_FUNCTION ("Undo normally undoes all the actions performed by a script. This puts a stage at the point in a script where it is called, so that a user-invoked undo will stop at this point, continuing when a further undo is invoked. Returns #t", DENEMO_SCHEME_PREFIX"StageForUndo", scheme_stage_for_undo);


  INSTALL_SCM_FUNCTION ("Takes a command name and returns the menu path to that command or #f if none",DENEMO_SCHEME_PREFIX"GetMenuPath", scheme_get_menu_path);


  INSTALL_SCM_FUNCTION ("Takes a command name and returns and id for it or #f if no command of that name exists",DENEMO_SCHEME_PREFIX"GetId", scheme_get_id);

  INSTALL_SCM_FUNCTION2 ("Takes a command name or command id and binding name and sets that binding on that command returns the command id that previously had the binding or #f if none",DENEMO_SCHEME_PREFIX"AddKeybinding", scheme_add_keybinding);

  INSTALL_SCM_FUNCTION ("Takes a command name and returns the label for the menu item that executes the command or #f if none",DENEMO_SCHEME_PREFIX"GetLabel", scheme_get_label);


  INSTALL_SCM_FUNCTION ("Returns the installed LilyPond version",DENEMO_SCHEME_PREFIX"GetLilyVersion", scheme_get_lily_version);
  INSTALL_SCM_FUNCTION ("Returns a boolean if the installed version of LilyPond is greater than or equal to the passed in version string",DENEMO_SCHEME_PREFIX"CheckLilyVersion", scheme_check_lily_version);



  INSTALL_SCM_FUNCTION ("Takes a string putting it on the status bar listing active filters",DENEMO_SCHEME_PREFIX"InputFilterNames", scheme_input_filter_names);

  }





/* Called from main for scheme initialization reasons.
   calls back to finish command line processing
*/
void inner_main(void*closure, int argc, char **argv){
  //g_print("Got inner main with  %d and %p\n", argc, argv);
  
  gint i;
  GError *error = NULL;
  
  rsvg_init();


  
  gchar *initial_file = process_command_line(argc, argv);

  //create window system
  create_window();

  create_scheme_identfiers();

  Denemo.prefs.cursor_highlight = TRUE;

  /* create the first tab */
  newtab (NULL, NULL);


  Denemo.prefs.profile = g_string_new("Simple");
  /* Initialize preferences */
  initprefs();
  /*ignore setting of mode unless user has explicitly asked for modal use */
  if(!Denemo.prefs.modal)
    Denemo.prefs.mode = INPUTEDIT|INPUTRHYTHM|INPUTNORMAL;//FIXME must correspond with default in prefops.c
  readHistory();
  populate_opened_recent ();
  //  g_print("init prefs run");
  if(Denemo.prefs.autoupdate)
    fetchcommands(NULL, NULL);

  gboolean save_default_keymap_file_on_entry = FALSE;
#define choice1 "Simple\nQuick start users: use this until you have read the manual\n"
#define choice2 "Arranger\nExperienced Users: transcribing music, playing music in, transposing etc"
#define choice3 "Composer\nExperienced Users: entering and modifying music, working with selections WASD use etc"
#define choice4 "Classic\nOld Denemo pc-keyboard interface."
#define choice5 "LilyPond\nExperienced Users with LilyPond knowledge"
#define choice6 "AllCommands\nUsers wanting to see the complete command set. No pre-defined shortcuts"

 
  if(uses_default_commandset()) {
    gchar *initialpref = Denemo.prefs.profile?Denemo.prefs.profile->str:NULL;
    gchar * never_again = NULL;
    if(initialpref) never_again = g_strdup_printf( "Use %s and do not show these choices again", initialpref);
    
    GString *choicestr = g_string_new("");
    gchar *thechoices = choice1"\0"choice2"\0"choice3"\0"choice4"\0"choice5"\0"choice6"\0";
    g_string_insert_len(choicestr, -1, thechoices, strlen(choice1)+1+strlen(choice2)+1+strlen(choice3)+1+strlen(choice4)+1+strlen(choice5)+1+strlen(choice6)+1);
    if(never_again)
      g_string_insert_len(choicestr, -1, never_again, strlen(never_again)+1);
    gchar *choice = get_option(choicestr->str, choicestr->len);
    if(choice==NULL)
      choice = choice1;
     {
      if(never_again && !strcmp(choice, never_again))
	save_default_keymap_file_on_entry = TRUE;
      else {
	choice = g_strdup(choice);
	gchar *c;
	for(c=choice;*c;c++)
	  if(*c=='\n')
	    *c='\0';
	g_string_assign(Denemo.prefs.profile, choice);
      }
    }
  }



  //Denemo.gui->si->undo_guard++;
  //denemo_scheme_init(initschemefile);
  //Denemo.gui->si->undo_guard--;
#ifdef _HAVE_JACK_
if (Denemo.prefs.midi_audio_output == Jack)
  init_jack();
#endif
  /* audio initialization */
  //ext_init (); 
  /* external players (midi...) */
#ifdef _HAVE_FLUIDSYNTH_
if (Denemo.prefs.midi_audio_output == Fluidsynth)
  fluidsynth_init(); 
#endif
#ifdef _HAVE_PORTAUDIO_
if (Denemo.prefs.midi_audio_output == Portaudio){
  /* Immediate Playback */
  if(Denemo.prefs.immediateplayback) {
    if( midi_init ()  )  {           /* Opens Denemo.prefs.sequencer, if this is set to an empty
				 string then the open fails and direct audio out is used for 
				immediate playback */
      //g_print("Initializing audio out\n");
      init_audio_out();
    }
  }
}
#endif    

    
  /* create scheme identifiers for check/radio item to activate the items (ie not just run the callback) */
  for(i=0;i<G_N_ELEMENTS(activatable_commands);i++) {
    install_scm_function (g_strdup_printf(DENEMO_SCHEME_PREFIX"%s", activatable_commands[i].str), (gpointer)activatable_commands[i].p);
  }

  init_keymap();

  load_default_keymap_file();

  if(save_default_keymap_file_on_entry)
    save_default_keymap_file();

  switch (Denemo.prefs.mode & ~MODE_MASK) {
  case INPUTINSERT:
    activate_action( "/MainMenu/ModeMenu/InsertMode");
    break;
  case INPUTEDIT:
    activate_action( "/MainMenu/ModeMenu/EditMode");
    break;
  case INPUTCLASSIC:
    activate_action( "/MainMenu/ModeMenu/ClassicMode");
    break;
  case 0:
    activate_action( "/MainMenu/ModeMenu/Modeless");
    break;
  default:
    activate_action( "/MainMenu/ModeMenu/Modeless");
    break;
  }

  switch(Denemo.prefs.mode & ~ENTRY_TYPE_MASK ) {
    case INPUTNORMAL:
      activate_action( "/MainMenu/ModeMenu/Note");
      break;
    case INPUTBLANK:
      activate_action( "/MainMenu/ModeMenu/Blank");
      break;
    case INPUTREST:
      activate_action( "/MainMenu/ModeMenu/Rest");
      break;

    default:
      break;
  }
  switch(Denemo.prefs.mode & ~ENTRY_FEEDBACK_MASK ) {

    case INPUTRHYTHM:
      //g_print("Activating rhythm Mode\n");
      activate_action( "/MainMenu/ModeMenu/Rhythm");
      break;

    default:
      break;
  }
  Denemo.gui->mode = Denemo.prefs.mode;
  if (Denemo.prefs.startmidiin)
    activate_action("/MainMenu/InputMenu/JackMidi");
  show_preferred_view();
  if(Denemo.prefs.cursor_highlight) {
    Denemo.prefs.cursor_highlight = FALSE;scheme_highlight_cursor(SCM_BOOL_T);
    //g_print("Cursor highlight is %d\n",Denemo.prefs.cursor_highlight);
  }
  gtk_key_snooper_install( (GtkKeySnoopFunc)dnm_key_snooper, NULL);
  Denemo.accelerator_status = FALSE;
 




 define_scheme_constants();

 load_scheme_init();

 if(!initial_file){   
   load_initdotdenemo();

 } else
   if (open_for_real (initial_file, Denemo.gui, FALSE, REPLACE_SCORE) == -1)
     ;// open_user_default_template(REPLACE_SCORE);
 
 {
   gchar *crash_file = g_build_filename(locatedotdenemo (), "crashrecovery.denemo", NULL);
   if(g_file_test(crash_file, G_FILE_TEST_EXISTS)) {
     GtkWidget *dialog = 
       gtk_dialog_new_with_buttons (NULL,
				    NULL,
				    GTK_DIALOG_DESTROY_WITH_PARENT,
				    GTK_STOCK_YES,
				    GTK_RESPONSE_ACCEPT,
				    
				    GTK_STOCK_DELETE,
				    GTK_RESPONSE_REJECT,
				    NULL);
     GtkWidget *label =
       gtk_label_new
       ("\nDenemo crashed, The open file has been recovered\n"
	"do you want to continue editing your work?\n");
     gtk_container_add (GTK_CONTAINER (GTK_DIALOG (dialog)->vbox),
			label);
     gtk_widget_show_all (dialog);
     gint result = gtk_dialog_run (GTK_DIALOG (dialog));
     g_debug ("Dialog result is %d\n", result);
     
     switch (result)
       {
       case GTK_RESPONSE_ACCEPT:
	 open_for_real (crash_file,  Denemo.gui, TRUE, REPLACE_SCORE);
	 score_status(Denemo.gui, TRUE);
	 //openfile (name, FALSE);
	 g_remove (crash_file);
	 break;
       case GTK_RESPONSE_CANCEL:
	 break;
       case GTK_RESPONSE_REJECT:
	 g_remove (crash_file);
	 break;
       }
     gtk_widget_destroy (dialog);
   }
 }

 //denemo_scheme_init(); this is done when opening init.denemo

/* Now launch into the main gtk event loop and we're all set */
 gtk_main();
}


static void selection_received (GtkClipboard *clipboard, const gchar *text, DenemoScriptParam *param) {
  if(!text) {
    warningdialog("No selection text available");
    param->status = FALSE;
    return;
  }
  param->string = g_string_new(text);
  param->status = TRUE;
  gtk_main_quit();
}

/* get the X selection into the param->string */
 
void get_clipboard(GtkAction * action, DenemoScriptParam *param) {
  GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
  gtk_clipboard_request_text (clipboard, (GtkClipboardTextReceivedFunc) selection_received, param);
  gtk_main();
}



GString *get_widget_path(GtkWidget *widget) {
  const gchar * name;
  GString *str = g_string_new("/");
  for(widget = gtk_widget_get_parent(widget);widget;widget = gtk_widget_get_parent(widget)){
    name = gtk_widget_get_name(widget);  
    g_string_prepend(str, name);
    g_string_prepend_c(str,'/');
  }
  g_print("String is %s\n", str->str);
  return str;
}

static gboolean action_callbacks(DenemoGUI* gui) {
  GList *callbacks = gui->callbacks;
  if(callbacks==NULL)
    return FALSE;
  gui->callbacks = NULL;//do this before calling the callbacks, so they cannot run twice
  for(;callbacks;callbacks=g_list_delete_link(callbacks, callbacks)){
    call_out_to_guile(callbacks->data);
    g_free(callbacks->data);
  }
  return TRUE;
}



/**
 * Close the current musical score (Denemo.gui) freeing all its movements (DenemoScore), releasing its memory and removing it from the global list Denemo.guis
 * Do not close the sequencer
 */
static gboolean
close_gui ()
{
  stop_midi_playback (NULL, NULL);// if you do not do this, there is a timer moving the score on which will hang
  activate_action("/MainMenu/InputMenu/KeyboardOnly");
  if(Denemo.autosaveid) {
    if(g_list_length(Denemo.guis)>1)
      g_print("Auto save being turned off");
    g_source_remove(Denemo.autosaveid);
    Denemo.autosaveid = 0;
  }

  free_movements(Denemo.gui);

  DenemoGUI *oldgui = Denemo.gui;
  //gtk_widget_destroy (Denemo.page);  //note switch_page from g_signal_connect (G_OBJECT(Denemo.notebook), "switch_page", G_CALLBACK(switch_page), NULL);
  gint index = g_list_index(Denemo.guis, oldgui);
  gtk_notebook_remove_page(GTK_NOTEBOOK(Denemo.notebook), index);
  g_print("Removed %d\n", index);
  Denemo.guis = g_list_remove (Denemo.guis, oldgui);//FIXME ?? or in the destroy callback??
  g_free (oldgui);
  if(Denemo.guis) {
    if(index>g_list_length(Denemo.guis)-1)
      index=g_list_length(Denemo.guis)-1;
    if(index<0)
      index = 0;

    Denemo.gui = g_list_nth_data(Denemo.guis, index);
    //g_print("Setting the first piece as your score\n");
    gtk_notebook_set_current_page (GTK_NOTEBOOK(Denemo.notebook), index);
  } else
    Denemo.gui = NULL; 
  return TRUE;
}

/* remove all the movements (ie the DenemoScore) leaving it with gui->si NULL */
void free_movements(DenemoGUI *gui)
{
  GList *g;

  for(g=gui->movements;g;g=g->next) {
    gui->si = g->data;
    gui->si->undo_guard = 1;//no undo as that is per movement
    free_score(gui);
  }
  gui->si = NULL;
  delete_directives(&gui->lilycontrol.directives);
  delete_directives(&gui->scoreheader.directives);
  delete_directives(&gui->paper.directives);
  g_list_free(gui->movements);
  gui->movements = NULL;
  if(gui->custom_scoreblocks) {
    GList *custom;
    for(custom=gui->custom_scoreblocks;custom;custom=custom->next) {
      g_string_free((GString*)(((DenemoScoreblock*)custom->data)->scoreblock), TRUE);
    }
    g_list_free(gui->custom_scoreblocks);
    gui->custom_scoreblocks=NULL;
  }
      /* any other free/initializations */

}

/**
* Wrapper function to close application when the quit
* menu item has been used
* 
*
*/
static void
closewrapper (GtkAction *action, gpointer param)
{
  GList *display;

  if(Denemo.accelerator_status) {
    if(confirm("You have made changes to the commands you have","Do you want to save the changes?"))
      save_accels();
  } 
  for (display = Denemo.guis; display != NULL;
       display = g_list_next (display))
    {
     Denemo.gui = (DenemoGUI *) display->data;
     if(close_gui_with_check (NULL, NULL) == FALSE)
       break;
  }
}

/**
 * callback from deleting window belonging to gui:
 * close window if check for unsaved data succeeds.
 * 
 */

static gboolean
delete_callback (GtkWidget * widget, GdkEvent * event)
{
  close_gui_with_check (NULL, NULL);
  return TRUE;
}
/**
 * callback to fetch up-to-date system commands from internet, denemo.org hardwired at present
 */
static void
fetchcommands (GtkAction *action, gpointer param)
{
  static gchar *location=NULL;
  location = g_build_filename(locatedotdenemo(), "download", "actions", NULL);
  gboolean err = g_mkdir_with_parents(location, 0770);
  if(err) {
    warningdialog(g_strdup_printf("Could not make folder %s for the downloaded commands", location));
    return;
  }

  g_print("location is %s\n", location);
  GError *error = NULL;
  gchar *arguments[] = {
  "wget",
  "-N",
  "-r",
  "-np",//only below the menus directory
  "-nH",//cut prefix
  "--cut-dirs=1",//cut download part of path
  DENEMO_DEFAULT_ANON_FTP,
  NULL
  };

  g_spawn_async (location,		/* dir */
		 arguments, NULL,	/* env */
		 G_SPAWN_SEARCH_PATH, /* search in path for executable */
		 NULL,	/* child setup func */
		 NULL,		/* user data */		
		 NULL,
		 &error);
  //FIXME create a callback to tell the user the result...
}


/**
 * callback to load system extra commands
 * if user has a local (possibly updated) set in ~/.denemo/downloads then that directory is used.
 */
static void
morecommands (GtkAction *action, gpointer param)
{
  static gchar *location=NULL;
  location = g_build_filename(locatedotdenemo(), "download", "actions", "menus", NULL);
  if(!g_file_test(location, G_FILE_TEST_EXISTS)){
    g_free(location);
    location = NULL;
  }
  if(location==NULL)
    location = g_build_filename(get_data_dir(), "actions", "menus", NULL);
  load_keymap_dialog_location (NULL, location);
  //#define WARNING_NEW_MENUS "Note: if you load a command that creates a new menu\nSome of the new commands may not work until you have exited\nand re-started denemo"
  //warningdialog(WARNING_NEW_MENUS);
  if(Denemo.last_merged_command && g_str_has_prefix(Denemo.last_merged_command, get_data_dir())) {
    g_free(location);
    location = g_strdup(Denemo.last_merged_command);
  }
}

/**
 * callback to load local extra commands
 * 
 */
static void
mycommands (GtkAction *action, gpointer param)
{
  static gchar *location=NULL;
  if(location==NULL)
    location = g_build_filename(locatedotdenemo(), "actions", "menus", NULL);

  if(Denemo.last_merged_command && g_str_has_prefix(Denemo.last_merged_command, locatedotdenemo())) {
    g_free(location);
    location = g_strdup(Denemo.last_merged_command);
  }
  load_keymap_dialog_location (NULL, location);
  // warningdialog(WARNING_NEW_MENUS);
  //g_print("The last was %s %s %s\n", Denemo.last_merged_command, location,  locatedotdenemo());
}



/**
 * Open in New Window callback 
 * Creates new view then opens file in the view
 */
void
openinnew (GtkAction *action, DenemoScriptParam *param)
{
  newtab (NULL, param);
  file_open_with_check (NULL, param);
  if(param && (param->status == FALSE))
     close_gui();
  set_title_bar(Denemo.gui);
}


/**
 * Close callback 
 * if user confirms close the current gui
 * if it is the last close the application.
 * return FALSE if gui was not closed, else TRUE
 */
gboolean
close_gui_with_check (GtkAction *action, gpointer param)
{
  DenemoGUI *gui = Denemo.gui;
  Denemo.prefs.mode = Denemo.gui->mode;
  if(action_callbacks(Denemo.gui))
    return FALSE; //Denemo.gui may have been closed, depends on script callbacks;

  //do not ask for confirm if scripted FIXME
  if ((!gui->notsaved) || (gui->notsaved && confirmbox (gui)))
    close_gui ();
  else 
    return FALSE;
  if(Denemo.guis==NULL) {
    storeWindowState ();
    writeHistory ();
    writeXMLPrefs(&Denemo.prefs);
#ifdef G_OS_WIN32
    CoUninitialize();
#endif

    /* ext_quit ();  clean players pidfiles (see external.c) DISUSED */
    exit(0);//do not use gtk_main_quit, as there may be inner loops active.
  }
  return TRUE;
}


static void
singleton_callback (GtkToolButton *toolbutton, RhythmPattern *r) {
  DenemoGUI *gui = Denemo.gui;
#define CURRP ((RhythmPattern *)gui->currhythm->data)
  if(gui->currhythm && CURRP)
    unhighlight_rhythm(CURRP);
  gui->currhythm = NULL;

  gui->rstep = r->rsteps;
  gui->cstep = NULL;

#define g (gui->rstep)
#define MODE (gui->mode)
  unhighlight_rhythm(gui->prevailing_rhythm);
  gui->prevailing_rhythm = r;
  highlight_rhythm(r);
  if((MODE &(INPUTEDIT|INPUTRHYTHM))) {
    gint save = MODE;
    MODE = INPUTINSERT|INPUTNORMAL;
    ((GtkFunction)(((RhythmElement*)g->data)->functions->data))(gui);
    displayhelper(gui); 
    MODE = save;
  }
#undef CURRP
#undef g
#undef MODE
}


static void pb_first (GtkWidget *button) {
  call_out_to_guile("(DenemoFirst)");
}
static void pb_go_back (GtkWidget *button) {
  call_out_to_guile("(DenemoGoBack)");
}
static void pb_previous (GtkWidget *button) {
  call_out_to_guile("(DenemoPrevious)");
}
static void pb_rewind (GtkWidget *button) {
  call_out_to_guile("(DenemoRewind)");
}
static void pb_stop (GtkWidget *button) {
  call_out_to_guile("(DenemoStop)");
}
static void pb_play (GtkWidget *button) {
  call_out_to_guile("(DenemoPlay)");
}
static void pb_pause (GtkWidget *button) {
  call_out_to_guile("(DenemoPause)");
}
static void pb_forward (GtkWidget *button) {
  call_out_to_guile("(DenemoForward)");
}
static void pb_next (GtkWidget *button) {
  call_out_to_guile("(DenemoNext)");
}
static void pb_go_forward (GtkWidget *button) {
  call_out_to_guile("(DenemoGoForward)");
}
static void pb_last (GtkWidget *button) {
  call_out_to_guile("(DenemoLast)");
}

static void pb_start_to_cursor (GtkWidget *button) {
  call_out_to_guile("(DenemoSetPlaybackStart)");
  gtk_widget_draw(Denemo.scorearea, NULL);
}

static void pb_end_to_cursor (GtkWidget *button) {
  call_out_to_guile("(DenemoSetPlaybackEnd)");
  gtk_widget_draw(Denemo.scorearea, NULL);
}

static void pb_loop (GtkWidget *button) {
  call_out_to_guile("(DenemoLoop)");
}

static void pb_tempo (GtkAdjustment *adjustment) {
  gdouble tempo;
  gdouble bpm =  gtk_adjustment_get_value(adjustment);
  tempo = (Denemo.gui->si->tempo>0)?
    bpm/Denemo.gui->si->tempo:1.0;
  scm_c_define("DenemoTempo::Value", scm_double2num(tempo));
  call_out_to_guile("(DenemoTempo)");
 
}
static void pb_volume (GtkAdjustment *adjustment) {
  gdouble volume = gtk_adjustment_get_value(adjustment);
  scm_c_define("DenemoVolume::Value", scm_double2num(volume));
  call_out_to_guile("(DenemoVolume)");
}
static void pb_set_range (GtkWidget *button) {
  call_out_to_guile("(DenemoSetPlaybackIntervalToSelection)");
}
static void pb_range (GtkWidget *button) {
  PlaybackRangeDialog();
}
static void pb_panic (GtkWidget *button) {
  playback_panic();
  reset_temperament();
}
static void track_delete(smf_track_t *track) {
  if(track==NULL)
    return;
  if(track->smf==NULL ) {
    smf_t *smf = smf_new();
    smf_add_track(smf, track);
    smf_delete(smf);
  } else
    smf_track_delete(track);
}

void finish_recording(void) {
  if((Denemo.gui->midi_destination & MIDIRECORD)) {
    Denemo.gui->midi_destination ^= MIDIRECORD;
    g_print("Showing");
    gtk_widget_show(deletebutton);
    gtk_widget_show(convertbutton);
  }
}

static void pb_midi_thru (GtkWidget *button) {
 Denemo.gui->midi_destination ^= MIDITHRU;
 if(Denemo.gui->midi_destination & MIDITHRU)
   gtk_button_set_label (GTK_BUTTON(button), _("MIDI In -> Recorder"));
 else
   gtk_button_set_label (GTK_BUTTON(button), _("MIDI In -> Score"));
}

static void pb_record (GtkWidget *button) {
 if( Denemo.gui->si->recorded_midi_track && !confirm("MIDI Recording", "Delete last recording?")) {
    return;
  }
 if(!(Denemo.gui->midi_destination & MIDITHRU))
   pb_midi_thru(midithrubutton);
 Denemo.gui->midi_destination |= MIDIRECORD;
 track_delete(Denemo.gui->si->recorded_midi_track);
 Denemo.gui->si->recorded_midi_track = smf_track_new();
 gtk_widget_hide(deletebutton);
 gtk_widget_hide(convertbutton);
 pb_play(playbutton);
 return;
}


static void pb_midi_delete (GtkWidget *button) {
  track_delete(Denemo.gui->si->recorded_midi_track);
  Denemo.gui->si->recorded_midi_track = NULL; 
  gtk_widget_hide (convertbutton);  
  gtk_widget_hide (button);
}

static void pb_midi_convert (GtkWidget *button) {

  call_out_to_guile("(DenemoConvert)");

  g_print("Finished midi convert\n");
}




/**
 * Rhythm callback select rhythm
 * inserts the rhythm if pitchless
 */
static void
select_rhythm_pattern(RhythmPattern *r) {
  DenemoGUI *gui = Denemo.gui;
#define CURRP ((RhythmPattern *)gui->currhythm->data)

  if(gui->currhythm && (CURRP != r)) {//Change the highlighting
    if(CURRP)
      unhighlight_rhythm(CURRP);
    else
      if(gui->rstep)
	unhighlight_rhythm(((RhythmElement*)gui->rstep->data)->rhythm_pattern);
  }
  
  gui->currhythm = g_list_find(gui->rhythms, r);
  gui->rstep = r->rsteps;
  gui->cstep = r->clipboard->data;
  
  gchar *text = ((RhythmElement*)gui->rstep->data)->icon;
  if(text) {
    GtkWidget *label = LABEL(CURRP->button);
    //g_print("markup is %s\n", ((RhythmElement*)g->data)->icon);
    gtk_label_set_markup(GTK_LABEL(label), text);
  }
  highlight_rhythm(CURRP);
#undef CURRP
}

static void
activate_rhythm_pattern(GtkToolButton *toolbutton, RhythmPattern *r) {
  select_rhythm_pattern(r);
 if((Denemo.gui->mode & INPUTEDIT))
   insert_note_following_pattern(Denemo.gui);//insert_clipboard(r->clipboard);
}


/* duration_code(gpointer function)
 * return an ascii code to indicate what duration (if any) function gives.
 * '0x0' means not a duration
 * chars 012345678 are the standard note durations
 * 
 */
gchar duration_code(gpointer fn) {
  return fn==(gpointer)insert_chord_0key ? '0':
    fn==(gpointer)insert_chord_1key ? '1':
    fn==(gpointer)insert_chord_2key ? '2':
    fn==(gpointer)insert_chord_3key ? '3':
    fn==(gpointer)insert_chord_4key ? '4':
    fn==(gpointer)insert_chord_5key ? '5':
    fn==(gpointer)insert_chord_6key ? '6':
    fn==(gpointer)insert_chord_7key ? '7':
    fn==(gpointer)insert_chord_8key ? '8':0;
}
/* modifier_code(gpointer function)
 * return an ascii code to indicate what modifier (if any) function gives.
 * '0x0' means not a valid modifier for a rhythmic duration
 * char '.' means a dotted note, '(' and ')' mean start and end slur
 * r to z are rests
 * others to be defined
 * 
 */
gchar modifier_code(gpointer fn) {
  return fn==(gpointer)start_triplet ? '~':
    fn==(gpointer)end_tuplet ? '|':
    fn==(gpointer)add_dot_key ? '.':
    fn==(gpointer)toggle_begin_slur ? '(':
    fn==(gpointer)toggle_end_slur ? ')': 
    fn==(gpointer)insert_rest_0key ? 'r':
    fn==(gpointer)insert_rest_1key ? 's':
    fn==(gpointer)insert_rest_2key ? 't':
    fn==(gpointer)insert_rest_3key ? 'u':
    fn==(gpointer)insert_rest_4key ? 'v':
    fn==(gpointer)insert_rest_5key ? 'w':
    fn==(gpointer)insert_rest_6key ? 'x':
    fn==(gpointer)insert_rest_7key ? 'y':
    fn==(gpointer)insert_rest_8key ? 'z':0;
}

gboolean code_is_a_duration(gchar code) {
  return code==0 || (code>='r' && code<='z');
}



/* add_to_rhythm appends to a rhythm pattern the callback function fn
   fn is a callback function
   returns TRUE if something was added
 */
static gboolean append_rhythm(RhythmPattern *r,  gpointer fn){     
	 RhythmElement *relement;
	 
	 int keyval = duration_code(fn);
	 if(keyval) {

	     relement = (RhythmElement*)g_malloc0(sizeof(RhythmElement));
	   
	   relement->functions = g_list_append(NULL, fn);

	     r->rsteps = g_list_append(r->rsteps, relement);
	     relement->rhythm_pattern = r;
	   return TRUE;
	 }
	 keyval = modifier_code(fn);
	 if(keyval) {
	   if(r->rsteps) {
	     relement = (RhythmElement *)(g_list_last(r->rsteps)->data);
	   }
	   else {
	     relement = (RhythmElement*)g_malloc0(sizeof(RhythmElement));
	   }
	   relement->functions = g_list_append(relement->functions, (gpointer)fn);
	   if(r->rsteps==NULL) {
	     r->rsteps = g_list_append(r->rsteps, relement);
	   }
	   relement->rhythm_pattern = r;
	   return TRUE;
	 }
	 return FALSE;
}


static void add_to_pattern(gchar **p, gchar c) {
  gchar *temp = g_strdup_printf("%s%c", *p, c);
  g_free(*p);
  *p = temp;
}

static void
attach_clipboard(RhythmPattern *r) {
 DenemoGUI *gui = Denemo.gui;
 DenemoScore *si = gui->si;
 if(si->markstaffnum) {
   push_clipboard ();
   copytobuffer(si);
   push_clipboard ();
   r->clipboard = pop_off_clipboard();
   pop_clipboard();
 }
}

static 
gint insert_pattern_in_toolbar(RhythmPattern *r) {
  DenemoGUI *gui = Denemo.gui;
  GtkWidget *toolbar = gtk_ui_manager_get_widget (Denemo.ui_manager, "/RhythmToolBar");
  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(r->button), -1);
  gtk_widget_show_all(GTK_WIDGET(r->button));
  gui->rstep = r->rsteps;
  gui->cstep = r->clipboard->data;
  gui->rhythms = g_list_append(gui->rhythms, r);
	
  if(gui->currhythm)
    unhighlight_rhythm((RhythmPattern *)gui->currhythm->data);
  gui->currhythm = g_list_last(gui->rhythms);
  highlight_rhythm((RhythmPattern *)gui->currhythm->data);
  g_signal_connect (G_OBJECT (r->button), "clicked",
		    G_CALLBACK (activate_rhythm_pattern), (gpointer)r);
  return g_list_length(gui->rhythms);//the index of the newly added snippet
}

static    void install_button_for_pattern(RhythmPattern *r, gchar *thelabel)
    {
      GtkToolButton *button;
      GtkWidget *label;
      button = (GtkToolButton *)gtk_tool_button_new(NULL, NULL);
      label = gtk_label_new(thelabel);
      gtk_label_set_use_markup (GTK_LABEL (label), TRUE);
      gtk_tool_button_set_label_widget (button, label);
      r->button = button;
    }


/* create_rhythm_cb
   This is overloaded for use as a callback (ACTION is a GtkAction) and
   as a call to set up the "singleton rhythms", 
   (rhythm patterns that are just one note or rest, used for
   ordinary note entry).
   if ACTION is a GtkAction*
        create a rhythm pattern from the current selection
        the rhythm is put in gui->
        a button is created in "/RhythmToolbar"
        and the pattern is added to gui->rhythms 
         with the first step of it put in gui->rstep
	add a clipboard with the selected music to the created rhythm pattern.
   if ACTION is one of the insert_chord_xkey insert_rest_xkey)
   functions
        a button is created in the /EntryToolbar (if not already present)
   

*/
static void 
create_rhythm_cb (GtkAction* action, gpointer param)     {
  DenemoGUI *gui = Denemo.gui;
  gboolean singleton = FALSE;// set TRUE if action is one of the insert_... functions.
  gboolean already_done = FALSE;// a singleton which has already been installed globally
  gboolean default_rhythm = FALSE;
  DenemoScore * si= gui->si;
  RhythmPattern *r = (RhythmPattern*)g_malloc0(sizeof(RhythmPattern));

  gchar *pattern = NULL;
    if(action ==  (gpointer)insert_chord_0key)
      pattern = g_strdup("0");
    if(action ==  (gpointer)insert_chord_1key)
      pattern = g_strdup("1");
    if(action ==  (gpointer)insert_chord_2key)
      pattern = g_strdup("2"), default_rhythm = TRUE;
    if(action ==  (gpointer)insert_chord_3key)
      pattern = g_strdup("3");
    if(action ==  (gpointer)insert_chord_4key)
      pattern = g_strdup("4");
    if(action ==  (gpointer)insert_chord_5key)
      pattern = g_strdup("5");
    if(action ==  (gpointer)insert_chord_6key)
      pattern = g_strdup("6");
    if(action ==  (gpointer)insert_chord_7key)
      pattern = g_strdup("7");
    if(action ==  (gpointer)insert_chord_8key)
      pattern = g_strdup("8");

    if(action ==  (gpointer)insert_rest_0key)
      pattern = g_strdup("r");
    if(action ==  (gpointer)insert_rest_1key)
      pattern = g_strdup("s");
    if(action ==  (gpointer)insert_rest_2key)
      pattern = g_strdup("t");
    if(action ==  (gpointer)insert_rest_3key)
      pattern = g_strdup("u");
    if(action ==  (gpointer)insert_rest_4key)
      pattern = g_strdup("v");
    if(action ==  (gpointer)insert_rest_5key)
      pattern = g_strdup("w");
    if(action ==  (gpointer)insert_rest_6key)
      pattern = g_strdup("x");
    if(action ==  (gpointer)insert_rest_7key)
      pattern = g_strdup("y");
    if(action ==  (gpointer)insert_rest_8key)
      pattern = g_strdup("z");
    if(pattern) {/* if we already have it globally we don't need it again
		    note we never delete the singleton rhythms */
      if(Denemo.singleton_rhythms[*pattern]) {
	g_free(r);
	r = Denemo.singleton_rhythms[*pattern];
	already_done = TRUE;
      }
      else {
	Denemo.singleton_rhythms[*pattern] = r;
	already_done = FALSE;
      }
      singleton=TRUE;
    }
  else
    pattern = g_strdup_printf("");
    if(!already_done)
      install_button_for_pattern(r, NULL);

  if(!singleton) {
    staffnode *curstaff;
    measurenode *curmeasure;
    gint i = si->firststaffmarked;
    attach_clipboard(r);
    curstaff = g_list_nth (si->thescore, i - 1);
    if(curstaff && i <= si->laststaffmarked) {
      int j,k;
      objnode *curobj;
      /* Measure loop.  */
      for (j = si->firstmeasuremarked, k = si->firstobjmarked,
	     curmeasure = g_list_nth (firstmeasurenode (curstaff), j - 1);
	   curmeasure && j <= si->lastmeasuremarked;
	   curmeasure = curmeasure->next, j++)
	{
	  for (curobj = g_list_nth ((objnode *) curmeasure->data, k);
	       /* cursor_x is 0-indexed */
	       curobj && (j < si->lastmeasuremarked
			  || k <= si->lastobjmarked);
	       curobj = curobj->next, k++)
	    {
	      gpointer fn;
	      gchar *temp;
	      DenemoObject *obj = (DenemoObject *) curobj->data;
	      switch(obj->type) {
	      case TUPCLOSE:
		fn = (gpointer)end_tuplet;
		add_to_pattern(&pattern, '|');
		append_rhythm(r, fn);
		break;
	      case TUPOPEN:
		switch(((tupopen*)obj->object)->denominator) {
		case 3:
		  fn=(gpointer)start_triplet;
		  add_to_pattern(&pattern, '~');
		  break;
		default:// need to create start_xxxtuplet() functions to go with start_triplet(), then they can go here.
		  fn = NULL;
		}
		append_rhythm(r, fn);
		break;
	      case CHORD:
		{
		  chord *ch = (chord*)obj->object;
		  
		  if(ch->notes) {
		    switch(ch->baseduration) {
		    case 0:
		      fn = insert_chord_0key;
		      break;
		    case 1:
		      fn = insert_chord_1key;
		      break;
		    case 2:
		      fn = insert_chord_2key;
		      break;
		    case 3:
		      fn = insert_chord_3key;
		      break;
		    case 4:
		      fn = insert_chord_4key;
		      break;
		    case 5:
		      fn = insert_chord_5key;
		      break;
		    case 6:
		      fn = insert_chord_6key;
		      break;
		    case 7:
		      fn = insert_chord_7key;
		      break;
		    case 8:
		      fn = insert_chord_8key;
		      break;
		    default:
		      g_warning("Handling unknown type of chord as whole note");
		      fn = insert_chord_0key;
		      break;
		    }
		    add_to_pattern(&pattern, duration_code(fn));
		    append_rhythm(r, fn);

		  } else {/* a rest */
		    switch(ch->baseduration) {
		    case 0:
		      fn = insert_rest_0key;
		      break;
		      case 1:
		      fn = insert_rest_1key;
		      break;
		      case 2:
		      fn = insert_rest_2key;
		      break;
		      case 3:
		      fn = insert_rest_3key;
		      break;
		      case 4:
		      fn = insert_rest_4key;
		      break;
		      case 5:
		      fn = insert_rest_5key;
		      break;
		      case 6:
		      fn = insert_rest_6key;
		      break;
		      fn = insert_rest_7key;
		      break;
		      fn = insert_rest_8key;
		      break;
		    default:
		      g_warning("Handling unknown type of rest as whole note rest");
		      fn = insert_rest_0key;
		      break;
		    }
		    add_to_pattern(&pattern, modifier_code(fn));
		    append_rhythm(r, fn);
		  } /* end of rests */
		  for (i=ch->numdots;i;i--) {
		    fn = add_dot_key;		    
		    add_to_pattern(&pattern, modifier_code(fn));
		    append_rhythm(r, fn);
		  }
		  if(ch->slur_begin_p) {
		    fn = (gpointer)toggle_begin_slur;
		    add_to_pattern(&pattern,'('); 
		    append_rhythm(r, fn);
		  }
		  if(ch->slur_end_p) {
		    fn = (gpointer)toggle_end_slur;
		    add_to_pattern(&pattern,')'); 
		    append_rhythm(r, fn);
		  }
		}
		break;
	      default:
		;
		
	      }
	      //g_print("Number of rhythms %d\n", g_list_length(r->rsteps));
	    } /* End object loop */	 
	} /* End measure loop */
    }//looking at selection
  if(strlen(pattern)==0) { // nothing useful selected
      warningdialog("No selection to create a music snippet from\nSee Edit->Select menu for selecting music to snip");
      gtk_widget_destroy(GTK_WIDGET(r->button));
      g_free(pattern);
      g_free(r);
      return;
    }
  } else { // singleton
    if(!already_done) 
      append_rhythm(r, action);
  }
  if(!already_done) {
    gchar *labelstr;
    if(pattern) {
      labelstr = music_font(pattern);
    }
    else
      return;  //FIXME memory leak of r - well pattern is never NULL
    //g_print("rsteps is %p entry is %s, %s\n", r->rsteps, pattern, labelstr);
    GtkWidget *label = gtk_tool_button_get_label_widget(r->button);
    gtk_label_set_markup(GTK_LABEL(label), labelstr);
    g_free(labelstr);
  }
  
  if(!singleton) {
    /* fill the r->rsteps with icons for each step, singletons have NULL icon */
    GList *g;  
    RhythmElement *el;
    gint i;
    for(g=r->rsteps, i=0;g;g=g->next, i++) {
      el = (RhythmElement*)g->data;
      if(i==0 && (*(pattern)<'0' || *(pattern)>'8') && g->next)
	g  = g->next;// pattern does not start with a note, so we skip to the second element, unless there are no notes
      while(*(pattern+i) && (*(pattern+i)<'0' || *(pattern+i)>'8'))
	i++;
      if(*(pattern+i)) {
	*(pattern+i) += 20;
	el->icon = music_font(pattern);
	*(pattern+i) -= 20;
      }
      //g_print("el->icon = %s step %d pattern %s\n", el->icon, i, pattern);
    }
  }
  if(!already_done)
    if(r->rsteps) {
      /* make the list circular */
      r->rsteps->prev = g_list_last(r->rsteps);
      g_list_last(r->rsteps)->next = r->rsteps;
    }
  if(r->rsteps==NULL)
    {
      gtk_widget_destroy(GTK_WIDGET(r->button));
      g_free(r);
      r = NULL;
    } else 	{
      if(singleton) {
	if(!already_done) {//When creating first gui only
	  GtkWidget *toolbar = gtk_ui_manager_get_widget (Denemo.ui_manager, "/EntryToolBar");
	  gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(r->button), -1);
	  gtk_widget_show_all(GTK_WIDGET(r->button));
	  /* gui->rstep = r->rsteps; */
	  g_signal_connect (G_OBJECT (r->button), "clicked",
			  G_CALLBACK (singleton_callback), (gpointer)r);
	  unhighlight_rhythm(r);
	}
	if(default_rhythm){
	  gui->prevailing_rhythm = r;
	  gui->rstep = r->rsteps;
	  gui->cstep = NULL;
	  highlight_rhythm(r);
	  //g_print("prevailing rhythm is %p\n",r);
	}	
      } else {//not singleton
	insert_pattern_in_toolbar(r);

      }      
    }
}



static void
save_accels (void) {
  save_default_keymap_file ();
  Denemo.accelerator_status = FALSE;
}


static 	void show_type(GtkWidget *widget, gchar *message);


static void configure_keyboard_idx (GtkWidget*w, gint idx) {
  DenemoGUI *gui = Denemo.gui;
  configure_keyboard_dialog_init_idx (NULL, gui, idx);
}

//static void toggleRecording (GtkWidget*w, gboolean *record) {
//  g_print("Recording was %d\n", *record);
//  *record = !*record;
//}

static void 
toggle_record_script(GtkAction *action, gpointer param) {
  Denemo.ScriptRecording = !Denemo.ScriptRecording;
}

static void appendSchemeText_cb(GtkWidget *widget, gchar *text) {
  appendSchemeText(text);
}



static void load_command_from_location(GtkWidget*w, gchar *filepath) {
  gchar *location = g_strdup_printf("%s%c", filepath, G_DIR_SEPARATOR);
  g_print("Calling the file loader with %s\n",location);
  load_keymap_dialog_location (w, location);
  g_free(location);
}


static void  attach_right_click_callback (GtkWidget *widget, GtkAction *action);

/* get the script for action from disk; 
 *   action an action loaded via load_xml_keymap() contains the menupath but no scheme script,
 */
gchar *instantiate_script(GtkAction *action){
  gchar *menupath = (gchar*)g_object_get_data(G_OBJECT(action), "menupath");
  const gchar *name = gtk_action_get_name(action);
  gchar *path =  g_build_filename (locatedotdenemo (), "actions","menus", menupath, NULL);
  gchar *filename = g_build_filename (path, name,  NULL);
  //  g_print("Filename %s\n", filename);
  if (load_xml_keymap (filename, TRUE)== -1) {
    g_free(filename);
    g_free(path);
    path = g_build_filename (locatedotdenemo (), "download", "actions", "menus", menupath, NULL);
    filename = g_build_filename (path, name,  NULL);				
    if (load_xml_keymap (filename, TRUE)== -1) {
      g_free(filename);
      g_free(path);
      path = g_build_filename (get_data_dir (), "actions", "menus", menupath, NULL);
      filename = g_build_filename (path, name,  NULL);
      if (load_xml_keymap (filename, TRUE)== -1) {
	g_free(path);
	g_free(filename);
	warningdialog("Unable to load the script");
	return NULL;
      }
    }
  }
  g_free(filename);
  filename = g_build_filename (path, INIT_SCM, NULL);
  if(g_file_test(filename, G_FILE_TEST_EXISTS))
    eval_file_with_catch(filename);//scm_c_primitive_load(filename);Use scm_c_primitive_load together with scm_internal_catch and scm_handle_by_message_no_exit instead. 
  g_free(filename);
  g_free(path);
  //g_print("Command loaded is following script:\n%s\n;;; end of loaded command script.\n", (gchar*)g_object_get_data(G_OBJECT(action), "scheme"));
  return  (gchar*)g_object_get_data(G_OBJECT(action), "scheme");
}


/* the callback for menu items that are scripts. The script is attached to the action,
tagged as "scheme".
The script may be empty, in which case it is fetched from actions/menus...

This call also ensures that the right-click callback is attached to all the proxies of the action, as there are problems trying to do this earlier, and it defines a scheme variable to give the name of the script being executed.
*/
gboolean
activate_script (GtkAction *action, gpointer param)
{
  DenemoGUI *gui = Denemo.gui;
  // the proxy list is NULL until the menu item is first called...
  //BUT if you first activate it with right button ....
  if(GTK_IS_ACTION(action)) {
    if(!g_object_get_data(G_OBJECT(action), "signal_attached")) {
      GSList *h = gtk_action_get_proxies (action);
      for(;h;h=h->next) {
	attach_right_click_callback(h->data, action);
	show_type(h->data, "type is ");
      }
    }
    gchar *text = (gchar*)g_object_get_data(G_OBJECT(action), "scheme");


    //FIXME use define_scheme_variable for this
    //define a global variable in Scheme (CurrentScript) to give the name of the currently executing script
    gchar *current_script = g_strdup_printf("(define CurrentScript \"%s\")\n", gtk_action_get_name(action));
    /*note that scripts must copy their name from CurrentScript into local storage before calling other scripts if they
      need it */
    scm_c_eval_string(current_script);
    g_free(current_script);


    if(*text==0)
      text = instantiate_script(action);
    if(text) {
      gboolean ret;
      stage_undo(gui->si, ACTION_STAGE_END);//undo is a queue so this is the end :)
      ret = (gboolean)!call_out_to_guile(text);
      stage_undo(gui->si, ACTION_STAGE_START);
      return ret; 
    }
  }
  else
    warningdialog("Have no way of getting the script, sorry");
  return FALSE;
}




/*pop up the help for passed command as info dialog
 */
static void popup_help(GtkWidget *widget, GtkAction *action) {
  const gchar *name = gtk_action_get_name(action);
  gint idx = lookup_command_from_name(Denemo.map, name);
  gchar *tooltip = idx>=0?(gchar *)lookup_tooltip_from_idx (Denemo.map, idx):"A menu for ...";

  tooltip = g_strdup_printf("Command: %s\n\nInformation:\n%s", name,  tooltip);
  infodialog (tooltip);
  g_free(tooltip);
  }

/* replace dangerous characters in command names */
static void  subst_illegals(gchar *myname) {gchar *c;// avoid whitespace etc
  for(c=myname;*c;c++)
    if(*c==' '||*c=='\t'||*c=='\n'||*c=='/'||*c=='\\') 
      *c='-';
  }



typedef struct ModifierAction {
  GtkAction *action;
  gint modnum;/* GdkModifierType number 0...12 */
  mouse_gesture gesture;/* if this is for press move or release */
  gboolean left;/* if this is for left or right mouse button */
}  ModifierAction;


// info->action is the action for which the mouse shortcut is to be set
static void setMouseAction(ModifierAction *info) {
  GString *modname = mouse_shortcut_name(info->modnum, info->gesture, info->left);
  gint command_idx = lookup_command_for_keybinding_name (Denemo.map, modname->str);
  GtkAction *current_action=NULL;
  gchar *title = NULL;
  gchar *prompt = NULL;
  if(command_idx >= 0) {
    current_action = (GtkAction *)lookup_action_from_idx(Denemo.map, command_idx);
    title = g_strdup_printf("The Command %s Responds to this Shortcut", lookup_name_from_idx(Denemo.map, command_idx));
    prompt = g_strdup_printf("Lose the shortcut %s for this?", modname->str);
  }
  if(current_action==NULL || confirm(title, prompt)) {
    remove_keybinding_from_name(Denemo.map, modname->str);//by_name 
    const gchar *name = gtk_action_get_name(info->action);
    command_idx = lookup_command_from_name (Denemo.map, name);
    if(command_idx >= 0)
      add_named_binding_to_idx (Denemo.map,  modname->str, command_idx, POS_LAST);
  }
  g_free(title);
  g_free(prompt);
  g_string_free(modname, TRUE);
}


static void placeOnButtonBar(GtkWidget *widget,  GtkAction *action) {
  gchar *name = (gchar *)gtk_action_get_name(action);
  gint idx = lookup_command_from_name(Denemo.map, name);
  gchar *label = (gchar*)lookup_label_from_idx(Denemo.map, idx);

  gchar *scheme = g_strdup_printf("\n;To remove the %s button delete from here\n(CreateButton \"Button%s\" \"%s\")\n(d-SetDirectiveTagActionScript  \"Button%s\" \"("DENEMO_SCHEME_PREFIX"%s)\")\n;;End of delete %s button",name, name, g_strescape(label, NULL), name, name, name);
  g_print("the scheme is \n%s\n", scheme);
  if(!call_out_to_guile(scheme))
    append_to_local_scheme_init(scheme);
  else
    warningdialog("Could not create button");
  g_free(scheme);
}
/* gets a name label and tooltip from the user, then creates a menuitem in the menu 
   given by the path myposition whose callback is the activate on the current scheme script.
*/

static void insertScript(GtkWidget *widget, gchar *insertion_point) {
  DenemoGUI *gui = Denemo.gui;
  gchar *myname, *mylabel, *myscheme, *mytooltip, *submenu;
  gchar *myposition = g_path_get_dirname (insertion_point);
  gchar *after = g_path_get_basename (insertion_point);
  gint idx = lookup_command_from_name (Denemo.map, after);
  //g_print("Saving with %s after %s\n", myposition, after);
  myname = string_dialog_entry (gui, "Create a new menu item", "Give item name (avoid clashes): ", "MyName");
  //FIXME check for name clashes

  if(myname==NULL)
    return;
  subst_illegals(myname);
  mylabel = string_dialog_entry (gui, "Create a new menu item", "Give menu label: ", "My Label");
  if(mylabel==NULL)
    return;

  mytooltip = string_dialog_entry (gui, "Create a new menu item", "Give explanation of what it does: ", "Prints my special effect");
  if(mytooltip==NULL)
    return;
  if(confirm("Create a new menu item", "Do you want the new menu item in a submenu?"))
    {
      submenu = string_dialog_entry (gui, "Create a new menu item", "Give a label for the Sub-Menu", "Sub Menu Label");
      if(submenu) {
	subst_illegals(submenu);
	myposition = g_strdup_printf("%s/%s", myposition, submenu);//FIXME leak
      }
    }
  
  myscheme = getSchemeText();

  //FIXME G_DIR_SEPARATOR in myposition???
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "menus", myposition, myname,  NULL);
  g_print("The filename built is %s from %s", filename, myposition);
  if((!g_file_test(filename, G_FILE_TEST_EXISTS))  || (g_file_test(filename, G_FILE_TEST_EXISTS) &&
						       confirm("Duplicate Name", "A command of this name is already available in your custom menus; Overwrite?"))) {
    gchar *dirpath = g_path_get_dirname(filename);
    g_mkdir_with_parents(dirpath, 0770);
    g_free(dirpath);
    //g_file_set_contents(filename, text, -1, NULL);
    save_script_as_xml (filename, myname, myscheme, mylabel, mytooltip, idx<0?NULL:after);
    load_xml_keymap(filename, TRUE);
    if(confirm("New Command Added", "Do you want to save this with your default commands?"))
      save_accels ();								    
  } else
    warningdialog("Operation cancelled");
  return;
}



static void append_scheme_call(gchar *func) {
  GtkTextIter enditer;
  GtkTextBuffer *buffer = gtk_text_view_get_buffer((GtkTextView*)(Denemo.ScriptView));
  //gtk_text_buffer_set_text(buffer,"",-1);
  gtk_text_buffer_get_end_iter (buffer,  &enditer);
  gchar *text = g_strdup_printf("(d-%s)\n",func);//prefix dnm_!!!!!!!
  gtk_text_buffer_insert(buffer, &enditer, text, -1);
  //g_print("Added %s\n", text);
  g_free(text); 
}




static void button_choice_callback(GtkWidget *w, gboolean *left ){
  g_print("left at %p is %d\n", left, *left);
  *left =  gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w));
  g_print("left at %p is now %d\n", left, *left);
}

static void button_move_callback(GtkWidget *w, mouse_gesture *g ){
  if( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)))
       *g = GESTURE_MOVE;
  // g_print("move %d\n", *g);
}
static void button_press_callback(GtkWidget *w, mouse_gesture *g ){
  if( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)))
       *g = GESTURE_PRESS;
  // g_print("press  %d\n", *g);
}
static void button_release_callback(GtkWidget *w, mouse_gesture *g ){
  if( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)))
       *g = GESTURE_RELEASE;
  // g_print("release %d \n", *g);
}



static void button_modifier_callback(GtkWidget *w, GdkEventButton *event,  ModifierAction *ma ){
  ma->modnum = event->state;
  // show_type(w, "button mod callback: ");
  GString *str = g_string_new("Keyboard:");
  append_modifier_name(str, ma->modnum);
  if(!ma->modnum)
    g_string_assign (str, "No keyboard modifier keys\nPress with modifier key to change");
  else
    g_string_append(str, "\nPress with modifier key to change");
  gtk_button_set_label (GTK_BUTTON(w), str->str);
  g_string_free(str,TRUE);
}



static void
mouse_shortcut_dialog(ModifierAction *info){
  GtkWidget *dialog = gtk_dialog_new_with_buttons ("Set Mouse Shortcut",
                                        GTK_WINDOW (Denemo.window),
                                        (GtkDialogFlags) (GTK_DIALOG_MODAL |
                                                       GTK_DIALOG_DESTROY_WITH_PARENT),
                                        GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
                                        NULL);
  GtkWidget *hbox = gtk_hbox_new (FALSE, 1);
  GtkWidget *vbox = gtk_vbox_new (FALSE, 1);  
  gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, TRUE, 0);
  gchar *name = (gchar*)gtk_action_get_name(info->action);
  gchar *prompt = g_strdup_printf("Setting mouse shortcut for %s", name);
  GtkWidget *label = gtk_label_new(prompt);
  g_free(prompt);
  gtk_box_pack_start (GTK_BOX (vbox), label, TRUE, TRUE, 0);
  GtkWidget *frame= gtk_frame_new( "Choose the mouse button");
  gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN);
  gtk_container_add (GTK_CONTAINER (vbox), frame);
  GtkWidget *vbox2 = gtk_vbox_new (FALSE, 8);
  gtk_container_add (GTK_CONTAINER (frame), vbox2);

  info->left = TRUE;
  GtkWidget *widget =   gtk_radio_button_new_with_label(NULL, "Left");
  g_signal_connect(G_OBJECT(widget), "toggled", G_CALLBACK(button_choice_callback), &info->left);
  gtk_box_pack_start (GTK_BOX (vbox2), widget, FALSE, TRUE, 0);
  GtkWidget *widget2  =   gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (widget), "Right");
  gtk_box_pack_start (GTK_BOX (vbox2), widget2, FALSE, TRUE, 0);
  

  frame= gtk_frame_new( "Choose mouse action");
  gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN);
  gtk_container_add (GTK_CONTAINER (vbox), frame);
  vbox2 = gtk_vbox_new (FALSE, 8);
  gtk_container_add (GTK_CONTAINER (frame), vbox2);
  info->gesture = GESTURE_PRESS;
  widget =   gtk_radio_button_new_with_label(NULL, "Press Button");
  g_signal_connect(G_OBJECT(widget), "toggled", G_CALLBACK(button_press_callback), &info->gesture);
  gtk_box_pack_start (GTK_BOX (vbox2), widget, FALSE, TRUE, 0);
  widget2  =   gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (widget), "Release Button");
  g_signal_connect(G_OBJECT(widget2), "toggled", G_CALLBACK(button_release_callback), &info->gesture);
  gtk_box_pack_start (GTK_BOX (vbox2), widget2, FALSE, TRUE, 0);
  widget2  =   gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON (widget), "Drag");
  g_signal_connect(G_OBJECT(widget2), "toggled", G_CALLBACK(button_move_callback), &info->gesture);
  gtk_box_pack_start (GTK_BOX (vbox2), widget2, FALSE, TRUE, 0);

  widget =   gtk_button_new_with_label("Hold Modifier Keys, Engage Caps or Num Lock\nand click here to set shorcut.");
  g_signal_connect(G_OBJECT(widget), "button-release-event", G_CALLBACK(button_modifier_callback), info);
  gtk_box_pack_start (GTK_BOX (vbox), widget, FALSE, TRUE, 0);

  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox,
		      TRUE, TRUE, 0);
  gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
  gtk_widget_show_all (dialog);
  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT){ 
    setMouseAction(info);
    Denemo.accelerator_status = TRUE;
  }
  gtk_widget_destroy (dialog);
}

static void  createMouseShortcut(GtkWidget *menu, GtkAction *action) {
  static ModifierAction info;
  info.action = action;
  info.gesture = GESTURE_PRESS;
  info.modnum = 0;
  info.left = TRUE;
  mouse_shortcut_dialog(&info);
}

/* get init.scm for the current path into the scheme text editor.
*/
static void get_initialization_script (GtkWidget *widget, gchar *directory) {
  GError *error = NULL;
  gchar *script;
  g_print("loading %s/init.scm into Denemo.ScriptView\n", directory);
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "menus", directory, INIT_SCM, NULL);
  if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
    g_free(filename);
    filename = g_build_filename(locatedotdenemo(), "download", "actions", "menus", directory, INIT_SCM, NULL);
    if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
      g_free(filename);
      filename = g_build_filename(get_data_dir(), "actions", "menus", directory, INIT_SCM, NULL);
      if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
	g_free(filename);
	return;
      }
    }
  }
  if(g_file_get_contents (filename, &script, NULL, &error))
    appendSchemeText(script);
  else
    g_warning("Could not get contents of %s\n", filename);
  g_free(script);
  g_free(filename);
}

/* write scheme script from Denemo.ScriptView into file init.scm in the user's local menupath.
*/
static void put_initialization_script (GtkWidget *widget, gchar *directory) {
  gchar *scheme;
  gchar *filename = g_build_filename(locatedotdenemo(), "actions", "menus", directory, INIT_SCM, NULL);
  if((!g_file_test(filename, G_FILE_TEST_EXISTS)) ||
     confirm("There is already an initialization script here", "Do you want to replace it?")){
    gchar *scheme = getSchemeText();
    if(scheme && *scheme) {
      FILE *fp = fopen(filename, "w");
      if(fp) {
	fprintf (fp, "%s", scheme);
	fclose(fp);
	if(confirm("Wrote init.scm", "Shall I execute it now?"))
	  call_out_to_guile(scheme);
      }
      else {
	warningdialog("Could not create init.scm;\n"
		      "you must create your scripted menu item in the menu\n"
		      "before you create the initialization script for it, sorry.");
      }
      g_free(scheme);
    }
  }
}

/* upload scripts for command/tag name.
Parameters: name the name of a command or a tag
            script the scheme script that the command runs, or an editscript for directives with tag name
	    init_script the scheme script that is run before the command runs, not used for tags
	    command the xml description of that command, or "" for tags
for tags:
   command is "" for an editscript and name is the tag for directives that the script edits
for commands:
   command is the command set file for merging the command as a new menu item
   the script is given in scheme and any initialization script for the menu is given in init_script
*/
static void 
upload_scripts(gchar *name, gchar *script, gchar *init_script, gchar *command, gchar *menupath, gchar *label, gchar *tooltip, gchar *after) {
  SCM func_symbol;
  SCM func;	
  func_symbol = scm_c_lookup("d-UploadRoutine");
  func = scm_variable_ref(func_symbol);    
#define ARG(s) s?scm_from_locale_string(s):scm_from_locale_string("")
  SCM list = scm_list_n( ARG(command), ARG(name), ARG(script), ARG(init_script),  ARG(menupath), ARG(label), ARG(tooltip), ARG(after), SCM_UNDEFINED);
  scm_call_1(func, list);
#undef ARG  
}



/* save the action (which must be a script),
   setting the script text to the script currently in the ScriptView
   The save is to the user's menu hierarchy on disk
*/
static void saveMenuItem (GtkWidget *widget, GtkAction *action) {
  gchar *name = (gchar *)gtk_action_get_name(action);
  gchar *menupath = g_object_get_data(G_OBJECT(action), "menupath");
  gchar *after = g_object_get_data(G_OBJECT(action), "after");
  gint idx = lookup_command_from_name(Denemo.map, name);
  gchar *tooltip = (gchar*)lookup_tooltip_from_idx(Denemo.map, idx);
  gchar *label = (gchar*)lookup_label_from_idx(Denemo.map, idx);
  
  gchar *filename = g_build_filename (locatedotdenemo (), "actions","menus", menupath, name,
				      NULL);
  gchar *scheme = getSchemeText();
  if(scheme && *scheme && confirm("Save Script", g_strconcat("Over-write previous version of the script for ", name, " ?", NULL))) {
    gchar *dirpath = g_path_get_dirname(filename);
    g_mkdir_with_parents(dirpath, 0770);
    g_free(dirpath);
    save_script_as_xml (filename, name, scheme, label, tooltip, after);
    g_object_set_data(G_OBJECT(action), "scheme", (gpointer)"");//
    instantiate_script(action);
  }
  else
    warningdialog("No script saved");
}


/* upload the action,
   from the user's menu hierarchy on disk, along with initialization script and menu item xml etc
*/
static void uploadMenuItem (GtkWidget *widget, GtkAction *action) {
  gchar *name = (gchar *)gtk_action_get_name(action);
  gchar *menupath = g_object_get_data(G_OBJECT(action), "menupath");
  gchar *after = g_object_get_data(G_OBJECT(action), "after");
  gint idx = lookup_command_from_name(Denemo.map, name);
  gchar *tooltip = (gchar*)lookup_tooltip_from_idx(Denemo.map, idx);
  gchar *label = (gchar*)lookup_label_from_idx(Denemo.map, idx);
  
  gchar *filename = g_build_filename (locatedotdenemo (), "actions","menus", menupath, name,
				      NULL);
  gchar *script = g_object_get_data(G_OBJECT(action), "scheme");
  gchar *xml;
  GError *error = NULL;
  g_file_get_contents(filename, &xml, NULL, &error);
  filename = g_build_filename (locatedotdenemo (), "actions", "menus", menupath, INIT_SCM,
					NULL);
  gchar *init_script;
  g_file_get_contents(filename, &init_script, NULL, &error);

  if(xml==NULL) xml = "";
  if(init_script==NULL) init_script = "";
  if(script==NULL) script = "";


  upload_scripts(name, script, init_script, xml, menupath, label, tooltip, after);

}


/* upload editscript for tag */
void
upload_edit_script(gchar *tag, gchar *script) {
  upload_scripts(tag,script,"","","","","","");
}


static const gchar *
locatebitmapsdir(void) {
  static gchar *bitmapsdir = NULL;
  gboolean err;
  if (!bitmapsdir)
    {
      bitmapsdir = g_build_filename (locatedotdenemo(), "actions", "bitmaps", NULL);
    }
  err = g_mkdir_with_parents(bitmapsdir, 0770);
  if(err) {
    warningdialog("Could not create .denemo/actions/bitmaps for your graphics for customized commands");
    g_free(bitmapsdir);
    bitmapsdir = g_strdup("");
  }
  return bitmapsdir;
}
static const gchar *
locatedownloadbitmapsdir(void) {
  static gchar *bitmapsdir = NULL;
  if (!bitmapsdir)
    {
      bitmapsdir = g_build_filename (locatedotdenemo(), "download", "actions", "bitmaps", NULL);
    }
  return bitmapsdir;
}

/* if a graphic file for name exists (local or downloaded or systemwide) create an icon for it called label
and return label, else return NULL
*/
gchar *
get_icon_for_name(gchar *name, gchar *label) {

  gchar *pngname = g_strconcat(name, ".png", NULL);
  gchar *filename = g_build_filename (locatebitmapsdir (), pngname,
				      NULL);
  if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
    g_free(filename);
    filename = g_build_filename (locatedownloadbitmapsdir(), pngname, 
				 NULL);
    if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
      g_free(filename);
      filename = g_build_filename (get_data_dir (), "actions", "bitmaps", pngname, 
				   NULL);
      if(!g_file_test(filename, G_FILE_TEST_EXISTS)) {
	g_free(filename);
	g_free(pngname);
	return NULL;
      }
    }
  }
  GError *error = NULL;
  GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file (filename, &error);
  g_free(filename);
  g_free(pngname);
  if(error) {
    warningdialog(error->message);		 
    return NULL;
  }
  static GtkIconFactory *icon_factory;
  if(!icon_factory){
    icon_factory = gtk_icon_factory_new ();
    gtk_icon_factory_add_default (icon_factory);
  }
  GtkIconSet *icon_set = gtk_icon_set_new_from_pixbuf (pixbuf);
  g_object_unref(pixbuf);
  gtk_icon_factory_add (icon_factory, label, icon_set);
  return label;
}



gchar *
create_xbm_data_from_pixbuf (GdkPixbuf *pixbuf, int lox, int loy, int hix, int hiy)
{
  int width, height, rowstride, n_channels;
  guchar *pixels, *p;

  n_channels = gdk_pixbuf_get_n_channels (pixbuf);

#ifdef DEBUG
  g_assert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
  g_assert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
  g_assert (gdk_pixbuf_get_has_alpha (pixbuf));
  g_assert (n_channels == 4);
#endif
  width = hix - lox;
  height = hiy - loy;      
  rowstride = gdk_pixbuf_get_rowstride (pixbuf);
  pixels = gdk_pixbuf_get_pixels (pixbuf);
  int x, y, i;

  unsigned char *chars = g_malloc0(sizeof(char) * width*height);//about 8 times too big!
  unsigned char * this = chars;
  for(i=0, y=loy;y<hiy;y++)
    {
      for(x=lox;x<hix;x++, i++) {
	this = chars + (i/8);
	gint set = ((pixels + y * rowstride + x * n_channels)[3]>0);
#ifdef G_OS_WIN32
	set = (set?0:1);//bizarrely the bitmaps come out inverted on windows
#endif

	*this += set<<i%8;
      }
      i = ((i+7)/8)*8;
    }
  return chars;
}

static GHashTable *bitmaps;
static void bitmap_table_insert(gchar *name, DenemoGraphic *xbm) {
  if(!bitmaps)
    bitmaps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);//FIXME is this right for GdkBitmap data?
  g_hash_table_insert(bitmaps, g_strdup(name), xbm);
}

static  GdkBitmap * create_bitmap_from_data(gchar *data, gint width, gint height) {
/*   static GdkColor white, black;gboolean init = FALSE; */
/*   if(!init) { */
/*     gdk_color_parse ("white", &white); */
/*     gdk_colormap_alloc_color (gdk_colormap_get_system (), &white, TRUE, TRUE); */
/*     gdk_color_parse ("black", &black); */
/*     gdk_colormap_alloc_color (gdk_colormap_get_system (), &black, TRUE, TRUE); */
/*   } */
  // return gdk_pixmap_create_from_data(NULL,data,  width, height, 1, &white, &black);
  return gdk_bitmap_create_from_data(NULL,data,  width, height);
}

static gboolean
loadGraphicFromFormat(gchar *basename, gchar *name, DenemoGraphic **xbm) {

  GError *error = NULL;
  gchar *filename = g_strconcat(name, ".png", NULL);
  GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file (filename, &error);
  g_free(filename);
  if(error) {
    g_error_free(error);
    error = NULL;
    gchar *filename = g_strconcat(name, ".svg", NULL);

    gchar *thename = g_malloc0(1000);
    // g_printf("Give name");
    //scanf("%s", thename);
    // filename = thename;
    //g_printf("Give scales x y");
    gfloat thescale=0.04, offx=500.0, offy=500.0;
    //scanf("%f%f", &offx, &offy);
    g_print("Got %f %f %f\n", thescale, offx, offy);
    RsvgHandle *handle = rsvg_handle_new_from_file(filename, &error);
    g_free(filename);
    if(handle==NULL) {
      if(error)
	g_warning("Could not open %s error %s\n", basename, error->message);
      else
	g_warning("Opening %s, Bug in librsvg:rsvg handle null but no error message", basename);
      return FALSE;
    }
    RsvgDimensionData thesize;
    rsvg_handle_get_dimensions(handle, &thesize); 
    
    g_print("size %d x %d", thesize.width, thesize.height);



    cairo_surface_t *surface =   (cairo_surface_t *)cairo_svg_surface_create_for_stream (NULL, NULL, (gdouble)thesize.width,  (gdouble)thesize.height); 
    cairo_t *cr = cairo_create(surface);
    cairo_translate(cr, offx, offy);
    cairo_scale(cr, thescale, -thescale);
    g_print("scaled %f %f %f\n", thescale, offx, offy);

    //cairo_translate(cr, 0.0, 0.0);
    //cairo_scale(cr, 1.0, 1.0);
    rsvg_handle_render_cairo(handle, cr);
    rsvg_handle_close(handle, NULL);
    g_object_unref(handle);
    cairo_pattern_t *pattern = cairo_pattern_create_for_surface (surface);
    cairo_pattern_reference(pattern); 
    cairo_destroy(cr);
    DenemoGraphic *graphic = g_malloc(sizeof(DenemoGraphic));
    graphic->type = DENEMO_PATTERN;
    graphic->width = thesize.width;
    graphic->height = thesize.height;
    graphic->graphic = pattern;
    bitmap_table_insert(basename, graphic);
    *xbm = graphic;
    return TRUE;
  }
  DenemoGraphic *graphic = g_malloc(sizeof(DenemoGraphic));
  graphic->type = DENEMO_BITMAP;
  GdkPixbuf *pixbufa = gdk_pixbuf_add_alpha (pixbuf, TRUE, 255, 255, 255);
  graphic->width = gdk_pixbuf_get_width(pixbufa);
  graphic->height = gdk_pixbuf_get_height(pixbufa);
  gchar *data = create_xbm_data_from_pixbuf(pixbufa, 0,0,graphic->width, graphic->height); 
  gpointer thedata = (gpointer)create_bitmap_from_data(data, graphic->width, graphic->height);
  graphic->graphic = thedata;
  bitmap_table_insert(basename, graphic);
  g_free(data);
  *xbm = graphic;
  return TRUE;
}


gboolean loadGraphicItem(gchar *name, DenemoGraphic **xbm ) {

  if (!name || !*name)
    return FALSE;
  if(bitmaps && (*xbm = (DenemoGraphic *) g_hash_table_lookup(bitmaps, name))) {
    
    return TRUE;
  }  
  gchar *filename = g_build_filename (locatebitmapsdir (), name,
				      NULL);
  
  if(1) {
    if(loadGraphicFromFormat(name, filename, xbm))
      return TRUE;
    g_free(filename);
    filename = g_build_filename (locatedownloadbitmapsdir(), name,
				      NULL);
  }
  if(1) {
    if(loadGraphicFromFormat(name, filename, xbm))
      return TRUE;
    g_free(filename);
    filename = g_build_filename (get_data_dir (), "actions",  "bitmaps", name,
				      NULL);
    if(loadGraphicFromFormat(name, filename, xbm))
      return TRUE;
  }
 {
    g_warning("Could not load graphic");
    //warningdialog("Could not load graphic");
  }


  return FALSE;
}

/* save the current graphic
*/
static void saveGraphicItem (GtkWidget *widget, GtkAction *action) {
  GError *error = NULL;
  gchar *name = (gchar *)gtk_action_get_name(action);
  gchar *pngname = g_strconcat(name, ".png", NULL);
  gchar *filename = g_build_filename (locatebitmapsdir (),  pngname,
				      NULL);
  //FIXME allow fileselector here to change the name
  gchar *msg = g_strdup_printf("Saving a graphic for use in the %s script", name);
  if( !g_file_test(filename,  G_FILE_TEST_EXISTS) || confirm (msg, "Replace current graphic?")) {
    guint width = Denemo.gui->xbm_width;
    guint height = Denemo.gui->xbm_height;
    
    
    GdkBitmap *bitmap = create_bitmap_from_data(Denemo.gui->xbm, width, height);

#if 0

    //  GdkBitmap *bitmap = gdk_bitmap_create_from_data(NULL, Denemo.gui->xbm, width, height);

    static GdkColor white, black;gboolean init = FALSE;
    if(!init) {
      gdk_color_parse ("white", &white);
      gdk_colormap_alloc_color (gdk_colormap_get_system (), &white, TRUE, TRUE);
      gdk_color_parse ("black", &black);
      gdk_colormap_alloc_color (gdk_colormap_get_system (), &black, TRUE, TRUE);
    }
    // GdkBitmap *bitmap = gdk_pixmap_create_from_data(NULL, Denemo.gui->xbm, width, height, 1, &white, &black);
GdkBitmap *bitmap = gdk_pixmap_create_from_data(NULL, Denemo.gui->xbm, width, height, 1, &black, &white);

 g_print("pixmap create");

#endif


    GdkPixbuf *pixbuf1 = gdk_pixbuf_get_from_drawable (NULL,  bitmap, NULL, 0,0,0,0, width, height);

    GdkPixbuf *pixbuf = gdk_pixbuf_add_alpha (pixbuf1, TRUE, 0,0,0);// 255, 255, 255);

    guchar *pixels;
    gint n_channels = gdk_pixbuf_get_n_channels (pixbuf);
    g_assert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
    g_assert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
    g_assert (gdk_pixbuf_get_has_alpha (pixbuf));
    g_assert (n_channels == 4);
    gint rowstride = gdk_pixbuf_get_rowstride (pixbuf);
    pixels = gdk_pixbuf_get_pixels (pixbuf);
    int x, y, i;
    for(i=0, y=0;y<height;y++)
      {
	for(x=0;x<width;x++, i++) {
	  gint set = !((pixels + y * rowstride + x * n_channels)[3]>0);
	  (pixels + y * rowstride + x * n_channels)[0] = 0xFF * set;
	  (pixels + y * rowstride + x * n_channels)[1] = 0xFF * set;
	  (pixels + y * rowstride + x * n_channels)[2] = 0xFF * set;
	}
      }


    gdk_pixbuf_save (pixbuf, filename, "png", &error, "compression", "2", NULL);


#if 0
      FILE *fp = fopen(filename,"wb");
      if(fp) {
      guchar whi, wlo, hhi, hlo;
      wlo = width&0xFF;
      whi = width>>8;
      hlo = height&0xFF;
      hhi = height>>8;
      
      fwrite(&wlo, 1, 1, fp);
      fwrite(&whi, 1, 1, fp);
      
      fwrite(&hlo, 1, 1, fp);
      fwrite(&hhi, 1, 1, fp);
      
      gint size = fwrite(Denemo.gui->xbm, 1, height*((width+7)/8)*8, fp);
    //g_print("Wrote %d bytes for %d x %d\n", size, width, height);


      g_free(msg);
      msg = g_strdup_printf("Saved graphic as file %s", filename);
      infodialog(msg);
      fclose(fp);  
    }
    else
      warningdialog("Could not write file");
#endif
  }

  g_free(pngname);
  g_free(msg);
  g_free(filename);
}

/* return a directory path for a system menu ending in menupath, or NULL if none exists
   checking user's download then the installed menus
   user must free the returned string*/
static gchar * get_system_menupath( gchar *menupath) {
  gchar * filepath = g_build_filename (locatedotdenemo(), "download", "actions", "menus", menupath, NULL);
  //g_print("No file %s\n", filepath);
  if(0!=g_access(filepath, 4)){
    g_free(filepath);
    filepath = g_build_filename (get_data_dir(), "actions", "menus", menupath, NULL);
  }
  return filepath;   
}


/*
  menu_click:
  intercepter for the callback when clicking on menu items for the set of Actions the Denemo offers.
  Left click runs default action, after recording the item in a scheme script if recording.
  Right click offers pop-up menu for setting shortcuts etc

*/
static gboolean menu_click (GtkWidget      *widget,
			  GdkEventButton *event,
			  GtkAction *action)
{
  keymap *the_keymap = Denemo.map;
  const gchar *func_name = gtk_action_get_name(action);
  //g_print("widget name %s action name %s\n", gtk_widget_get_name(widget), func_name);

  // GSList *h = gtk_action_get_proxies (action);
  //g_print("In menu click action is %p h is %p\n",action, h);



  gint idx = lookup_command_from_name (the_keymap, func_name);
  //g_print("event button %d, idx %d for %s recording = %d scm = %d\n", event->button, idx, func_name, Denemo.ScriptRecording,g_object_get_data(G_OBJECT(action), "scm") );
  if (event->button != 3) //Not right click
    if(Denemo.ScriptRecording)
      if(idx_has_callback(the_keymap, idx)){
	append_scheme_call((gchar*)func_name);
      }

  if (event->button != 3)
    return FALSE;
 

#if 0
  /* This idx is -1 for the toggles and radio entries because they share a callback function. If we want to allow setting keybindings, getting help etc. for these then we would need to re-work all the radio action entries code using generate_source.c. Instead at the moment we have just defined scheme callback functions d-EditMode etc. using a hand-created array activatable_commands earlier in this file.
   It is also for menus themselves, so we process the case further.*/
  if (idx == -1)
    return TRUE;
#endif

  GtkWidget *menu = gtk_menu_new();
  gchar *labeltext = g_strdup_printf("Help for %s", func_name);
  GtkWidget *item = gtk_menu_item_new_with_label(labeltext);
  g_free(labeltext);
  gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
  g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(popup_help), (gpointer)action);


  /* "drag" menu item onto button bar */

   item = gtk_menu_item_new_with_label("Place Command on Button Bar");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(placeOnButtonBar), action);


  if(idx!=-1) {
    item = gtk_menu_item_new_with_label("Create Mouse Shortcut");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(createMouseShortcut), action);
    item = gtk_menu_item_new_with_label("Edit Shortcuts\nSet Mouse Pointers\nHide/Delete Menu Item");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(configure_keyboard_idx), (gpointer)idx);
    item = gtk_menu_item_new_with_label("Save Command Set");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(save_default_keymap_file), action);


    item = gtk_separator_menu_item_new();
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
  }//idx!=-1

  gchar *myposition = g_object_get_data(G_OBJECT(widget), "menupath");// applies if it is a built-in command
 g_print("position from built in is %s\n", myposition);
  if(!myposition)
    myposition = g_object_get_data(G_OBJECT(action), "menupath");//menu item runs a script
  //g_print("Connecting to %s\n", g_object_get_data(G_OBJECT(widget), "menupath"));

  //g_print("position is %s\n", myposition);
  if(myposition == NULL) {
    g_warning("Cannot find the position of this menu item %s in the menu system\n", func_name);
    return TRUE;
  }
  static gchar *filepath;// static so that we can free it next time we are here.
  if(filepath)
    g_free(filepath);
  filepath = get_system_menupath(myposition);
  if(0==g_access(filepath, 4)) {
    //g_print("We can look for a menu item in the path %s\n", filepath);
    item = gtk_menu_item_new_with_label("More Commands");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(load_command_from_location), (gpointer)filepath);
  }

  gchar *scheme = g_object_get_data(G_OBJECT(action), "scheme");
  if(scheme) {
    if(*scheme==0)
      scheme = instantiate_script(action);
    if(scheme) {
      item = gtk_menu_item_new_with_label("Get Script");
      gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
      g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(appendSchemeText_cb), scheme);
    }
    item = gtk_menu_item_new_with_label("Save Script");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(saveMenuItem), action);
    if(Denemo.gui->xbm) {
      item = gtk_menu_item_new_with_label("Save Graphic");
      // GtkSettings* settings = gtk_settings_get_default();
      // gtk_settings_set_long_property  (settings,"gtk-menu-images",(glong)TRUE, "XProperty");
      //item = gtk_image_menu_item_new_from_stock("Save Graphic", gtk_accel_group_new());
      item = gtk_image_menu_item_new_from_stock("Save Graphic"/*GTK_STOCK_OK*/, NULL);
      
      gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
      g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(saveGraphicItem), action);
    }
    item = gtk_menu_item_new_with_label("Upload this Script to denemo.org");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(uploadMenuItem), action);

  }
  if (GTK_WIDGET_VISIBLE(gtk_widget_get_toplevel(Denemo.ScriptView))) {
    item = gtk_menu_item_new_with_label("Save Script as New Menu Item");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    static gchar *insertion_point;
    if(insertion_point)
      g_free(insertion_point);
    insertion_point = g_build_filename(myposition, func_name, NULL);
    //g_print("using %p %s for %d %s %s\n", insertion_point, insertion_point, idx, myposition, func_name);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(insertScript), insertion_point);
  }


  /* options for getting/putting init.scm */

    item = gtk_menu_item_new_with_label("Get Initialization Script for this Menu");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(get_initialization_script), myposition);

    item = gtk_menu_item_new_with_label("Put Script as Initialization Script for this Menu");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
    g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(put_initialization_script), myposition);



  /* a check item for showing script window */
  item = gtk_check_menu_item_new_with_label("Show Current Script");
  gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), GTK_WIDGET_VISIBLE(gtk_widget_get_toplevel(Denemo.ScriptView)));
  gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
  //FIXME the next statement triggers a warning that ToggleScript is not a registered denemo commad - correct, since we do not make the toggles available as commands since using such a command would make the check boxes out of step, instead we install function that activate the menuitem.
  gtk_action_connect_proxy(gtk_ui_manager_get_action (Denemo.ui_manager, "/MainMenu/ViewMenu/ToggleScript"), item);


  gtk_widget_show_all(menu);
  gtk_menu_popup (GTK_MENU(menu), NULL, NULL, NULL, NULL,0, gtk_get_current_event_time()); 
  // configure_keyboard_dialog_init_idx (action, gui, idx);
  return TRUE;
}



static void	  color_rhythm_button(RhythmPattern *r, const gchar *color) {
  if(r==NULL) return;
  GdkColor thecolor;
  gdk_color_parse (color, &thecolor);
  gtk_widget_modify_fg (gtk_tool_button_get_label_widget(GTK_TOOL_BUTTON(r->button)), GTK_STATE_NORMAL, &thecolor);
  //bg does not work, and setting the label in a GtkEvent box gave a problem on some build - R.Rankin patched for this and so we have to use fg
}
void	  highlight_rhythm(RhythmPattern *r) {
  //g_print("highlight\n");
  color_rhythm_button(r, "black");
}

void	  unhighlight_rhythm(RhythmPattern *r) {
  //g_print("Unhighlight\n");
  color_rhythm_button(r, "gray");
}


/*
 

  
*/
void	highlight_rest(DenemoGUI *gui, gint dur) {  

  //g_print("highlight rest");
      if(gui->currhythm) {
	unhighlight_rhythm((RhythmPattern *)gui->currhythm->data);	
      }
      gui->currhythm = NULL;
      gui->cstep = NULL;
      gui->rstep = Denemo.singleton_rhythms['r'+dur]->rsteps;
      unhighlight_rhythm(gui->prevailing_rhythm);
      gui->prevailing_rhythm = Denemo.singleton_rhythms['r'+dur];
      highlight_rhythm(gui->prevailing_rhythm);

}

void	highlight_duration(DenemoGUI *gui, gint dur) {  

  //g_print("higlight duration");
      if(gui->currhythm) {
	unhighlight_rhythm((RhythmPattern *)gui->currhythm->data);	
      }
      gui->currhythm = NULL;
      gui->cstep = NULL;
      gui->rstep =  Denemo.singleton_rhythms['0'+dur]->rsteps;
      unhighlight_rhythm(gui->prevailing_rhythm);
      gui->prevailing_rhythm = Denemo.singleton_rhythms['0'+dur];
      highlight_rhythm(gui->prevailing_rhythm);
}




/*
 * delete a rhythmic pattern and its button
 * 
 */
static void
delete_rhythm_cb (GtkAction * action, gpointer param)
{
  DenemoGUI *gui = Denemo.gui;
  if(gui->mode&(INPUTEDIT) == 0)
    return;
  if(gui->currhythm==NULL)
    return;
  RhythmPattern *r =(RhythmPattern *)gui->currhythm->data;
  
  free_clipboard(r->clipboard);
  r->clipboard = NULL;
  if(r->name) {
    gchar *command = g_strdup_printf("(define Snippet::%s 0)", r->name);
    call_out_to_guile(command);
    g_free(command);
  }
    
  gtk_widget_destroy(GTK_WIDGET(r->button));
  /* list is circular, so before we free it we have to break it */
  r->rsteps->prev->next = NULL;
  r->rsteps->prev = NULL;
  GList *g;
  for(g=r->rsteps;g;g=g->next)
    g_free(g->data);
  g_list_free(r->rsteps);
  g_free(r);
  //g_print("length %d\n", g_list_length(gui->rhythms));
  gui->rhythms = g_list_remove(gui->rhythms, gui->currhythm->data);
  //g_print("length %d %p\n", g_list_length(gui->rhythms), gui->rhythms);
  gui->currhythm = g_list_last(gui->rhythms);

  if(gui->currhythm == NULL) {
   gui->rstep = NULL;
   gui->cstep = NULL;
  }
  else {
    highlight_rhythm(gui->currhythm->data);
    gui->rstep = ((RhythmPattern *)gui->currhythm->data)->rsteps;
    gui->cstep = ((RhythmPattern *)gui->currhythm->data)->clipboard->data;
  }
  update_scheme_snippet_ids();
}



/*
 * workaround for glib<2.10
 */
static
void  attach_action_to_widget (GtkWidget *widget, GtkAction *action, DenemoGUI *gui) {
  g_object_set_data(G_OBJECT(widget), "action", action);
}

/* attaches a button-press-event signal to the widget with the action as data
   for use in the callback */
static void  attach_right_click_callback (GtkWidget *widget, GtkAction *action) {



  gtk_widget_add_events (widget, (GDK_BUTTON_PRESS_MASK)); //will not work because label are NO_WINDOW
  g_signal_connect(G_OBJECT(widget), "button-release-event", G_CALLBACK (menu_click), action);

  //g_print("menu click set on %s GTK_WIDGET_FLAGS %x\n", gtk_action_get_name(action), GTK_WIDGET_FLAGS(widget));
  //show_type(widget, "Type is ");

  g_object_set_data(G_OBJECT(action), "signal_attached", action);//Non NULL to indicate the signal is attached
}



static void dummy(void) {
  call_out_to_guile("(d-Insert2)");
  call_out_to_guile("(d-Insert2)");
  call_out_to_guile("(d-Insert2)");
  call_out_to_guile("(d-Insert2)");
  call_out_to_guile("(d-Insert2)");
  return;
}

/**
 * Menu entries with no shortcut keys, tooltips, and callback functions
 */
GtkActionEntry menu_entries[] = {
#include "entries.h"
  {"Stub",  NULL, N_(" "), NULL, N_("Does nothing"), G_CALLBACK (dummy)}

  };

//Get number of menu entries
//gint n_menu_items = G_N_ELEMENTS (menu_entries);

static
GtkWidget *get_edit_menu_for_mode(gint mode) {
  return NULL;
  if(mode&INPUTEDIT)
    return Denemo.EditModeMenu;
  if(mode&INPUTINSERT)
    return Denemo.InsertModeMenu;
  if(mode&INPUTCLASSIC)
    return Denemo.ClassicModeMenu;
  return Denemo.ModelessMenu;
}

/**
 *  callback changing mode  gui->mode
 *
 */
static void
change_mode (GtkRadioAction * action, GtkRadioAction * current) {
  DenemoGUI *gui = Denemo.gui;
gint val = gtk_radio_action_get_current_value (current);
 GtkWidget *menu = get_edit_menu_for_mode(gui->mode);
 if(menu)
   gtk_widget_hide(menu);
 gui->mode=((gui->mode&MODE_MASK)|val);
 menu = get_edit_menu_for_mode(gui->mode);
 if(menu)
   gtk_widget_show(menu);
 write_status(gui);
 
}


void activate_action(gchar *path) {
   GtkAction *a;
   a = gtk_ui_manager_get_action (Denemo.ui_manager, path);
   if(a)
   gtk_action_activate(a);
   else 
     g_warning("Internal error, denemogui.xml out of step with literal %s in %s\n", path, __FILE__);
 }

/**
 *  callback changing the input source (keyboard only/audio/midi)
 *
 */

static void
change_input_type (GtkRadioAction * action, GtkRadioAction * current) {
  DenemoGUI *gui = Denemo.gui;
gint val = gtk_radio_action_get_current_value (current);
 gboolean fail=FALSE;
 switch(val) {
 case INPUTKEYBOARD:
   if(gui->input_source==INPUTAUDIO) {
     // g_print("Stopping audio\n");
     stop_pitch_input();
   }
   if(gui->input_source==INPUTMIDI) {
     // g_print("Stopping midi\n");
     stop_pitch_input();
   }
   gui->input_source=INPUTKEYBOARD;
   g_print("Input keyboard");
   break;
 case INPUTAUDIO:
   //g_print("Starting audio\n");
   if(gui->input_source==INPUTMIDI) {
     //g_print("Stopping midi\n");
     stop_pitch_input();
   }
   gui->input_source=INPUTAUDIO;
   if(setup_pitch_input()){
     fail = TRUE;
     warningdialog("Could not start Audio input");
     gtk_radio_action_set_current_value(current, INPUTKEYBOARD);
   } else
     start_pitch_input();
   break;
 case INPUTMIDI:
   //g_print("Starting midi\n");
   if(gui->input_source==INPUTAUDIO) {
     //g_print("Stopping audio\n");
     stop_pitch_input();
   }
   gui->input_source=INPUTMIDI;
  if (Denemo.prefs.midi_audio_output == Portaudio)
   start_midi_input();
  else if  (Denemo.prefs.midi_audio_output == None)
   fail = TRUE;
  else if (Denemo.prefs.midi_audio_output == Jack)
   fail = init_midi_input();
  else if (Denemo.prefs.midi_audio_output == Fluidsynth)
   fail = init_midi_input();
  //g_print("Midi start - %d\n", fail);
   break;
 default:
   g_warning("Bad Value\n");
   break;
 }
 if(fail)
   gtk_radio_action_set_current_value(current, INPUTKEYBOARD);
   else
     write_input_status();
}
/**
 *  callback changing type of entry part of gui->mode,
 * depending on the entry type it switches mode part of gui->mode to Classic mode for entering rests and to Insert for entering notes. FIXME could switch to prefs value.
 *
 */
static void
change_entry_type (GtkRadioAction * action, GtkRadioAction * current) {
  DenemoGUI *gui = Denemo.gui;
gint val = gtk_radio_action_get_current_value (current);
 switch(val) {
#define SET_MODE(m)  (gui->mode=((gui->mode&ENTRY_TYPE_MASK)|m))
 case INPUTREST:
   SET_MODE(INPUTREST);
   activate_action("/MainMenu/ModeMenu/ClassicMode");

   break;
 case INPUTNORMAL:
   SET_MODE(INPUTNORMAL);
   activate_action( "/MainMenu/ModeMenu/InsertMode");
   break;
 case INPUTBLANK:
   SET_MODE(INPUTBLANK);
   activate_action( "/MainMenu/ModeMenu/ClassicMode");
   break;
 case INPUTRHYTHM|INPUTNORMAL:
   SET_MODE(INPUTRHYTHM|INPUTNORMAL);
   activate_action( "/MainMenu/ModeMenu/EditMode");
   break;
 }
#undef SET_MODE

write_status(gui);
 //g_print("Mode is %x masks %x %x\n",ENTRY_TYPE_MASK, MODE_MASK, gui->mode);
}

/* callback: if not Insert mode set Insert mode else set Edit mode */
static void toggle_edit_mode (GtkAction * action, gpointer param){
  DenemoGUI *gui = Denemo.gui;
  static gint mode=INPUTINSERT;
  if(gui->mode&INPUTEDIT){
    switch(mode & ~MODE_MASK ) {
    case INPUTINSERT:
      activate_action( "/MainMenu/ModeMenu/InsertMode");
      break;
    case INPUTCLASSIC:
      activate_action( "/MainMenu/ModeMenu/ClassicMode");
      break;
    case 0:
      activate_action( "/MainMenu/ModeMenu/Modeless");
      break;
    default:
      ;
    }
  } else {
    mode = gui->mode;// remember mode for switching back
    activate_action( "/MainMenu/ModeMenu/EditMode");
  }
}

/* callback: if rest entry make note entry and vv */
static void toggle_rest_mode (GtkAction * action, gpointer param){
  DenemoGUI *gui = Denemo.gui;
  static gint mode=INPUTNORMAL;
  if(gui->mode&INPUTREST){
    switch(mode & ~ENTRY_TYPE_MASK ) {
    case INPUTNORMAL:
      activate_action( "/MainMenu/ModeMenu/Note");
      break;
    case INPUTBLANK:
      activate_action( "/MainMenu/ModeMenu/Blank");
      break;
    default:
      ;
    }
  } else {
    mode = gui->mode;// remember mode for switching back
    activate_action( "/MainMenu/ModeMenu/Rest");
  }
}


/* callback: if rhythm entry make note entry and vv */
static void toggle_rhythm_mode (GtkAction * action, gpointer param){
  DenemoGUI *gui = Denemo.gui;
#if 1
  //g_print("Was mode %x\n", gui->mode);
   if(gui->mode&INPUTRHYTHM)
     gui->mode &= ~INPUTRHYTHM;
   else {
     gui->mode |= INPUTRHYTHM;
    activate_action( "/MainMenu/ModeMenu/EditMode"); 
   }
   // g_print("Now mode %x\n", gui->mode);
#else
  static gint mode=INPUTNORMAL;
  if(gui->mode&INPUTRHYTHM){
    switch(mode & ~ENTRY_TYPE_MASK ) {
    case INPUTNORMAL:
      activate_action( "/MainMenu/ModeMenu/Note");
      break;
    default:
      ;
    }
  } else {
    mode = gui->mode;// remember mode for switching back, breaks with multi gui FIXME
    activate_action( "/MainMenu/ModeMenu/Rhythm");
  }
#endif
}

/**
 *  Function to toggle the visibility of the LilyPond text window. It refreshes 
 *  the text if needed
 */
static void
toggle_lilytext (GtkAction * action, gpointer param) {
  DenemoGUI *gui = Denemo.gui;
  //if(!gui->textview)
   refresh_lily_cb(action, gui);
 if(!GTK_WIDGET_VISIBLE(gui->textwindow))
   gtk_widget_show/*_all*/(gui->textwindow);
 else
   gtk_widget_hide(gui->textwindow);
 //g_print("toggling lily window");
}


/**
 *  Function to toggle the visibility of the Scheme text window. 
 */
static void
toggle_scheme (GtkAction * action, gpointer param) {
  DenemoGUI *gui = Denemo.gui;
  GtkWidget *textwindow = gtk_widget_get_toplevel(Denemo.ScriptView);
 if(!GTK_WIDGET_VISIBLE(textwindow))
   gtk_widget_show_all(textwindow);
 else
   gtk_widget_hide_all(textwindow);
 // g_print("toggling scheme window");
}




/**
 *  Function to toggle whether rhythm toolbar is visible 
 *  (no longer switches keymap to Rhythm.keymaprc when toolbar is on back to standard when off.)
 *  
 */
static void
toggle_rhythm_toolbar (GtkAction * action, gpointer param)
{
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/RhythmToolBar");
 // g_print("Callback for %s\n", g_type_name(G_TYPE_FROM_INSTANCE(widget)));
  if ((!action) || GTK_WIDGET_VISIBLE (widget))
    {
      
      gtk_widget_hide (widget);
    }
  else
    {

      gtk_widget_show (widget);
      /* make sure we are in Insert and Note for rhythm toolbar */
      // activate_action( "/MainMenu/ModeMenu/Note");
      //activate_action( "/MainMenu/ModeMenu/InsertMode");
    }
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.rhythm_palette = GTK_WIDGET_VISIBLE (widget);
}

/**
 *  Function to toggle whether main toolbar is visible 
 *  
 * 
 */
static void
toggle_toolbar (GtkAction * action, gpointer param) {
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ToolBar");
  if ((!action) || GTK_WIDGET_VISIBLE (widget))
      gtk_widget_hide (widget);
  else
      gtk_widget_show (widget);
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.toolbar = GTK_WIDGET_VISIBLE (widget);
}

/**
 *  Function to toggle whether playback toolbar is visible 
 *  
 * 
 */
static void
toggle_playback_controls (GtkAction * action, gpointer param) {
  GtkWidget *widget;
  widget = Denemo.playback_control;
  if ((!action) ||GTK_WIDGET_VISIBLE (widget))
      gtk_widget_hide (widget);
  else
      gtk_widget_show (widget);
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.playback_controls = GTK_WIDGET_VISIBLE (widget);
}
/**
 *  Function to toggle whether playback toolbar is visible 
 *  
 * 
 */
static void
toggle_midi_in_controls (GtkAction * action, gpointer param) {
  GtkWidget *widget;
  widget = Denemo.midi_in_control;
  if ((!action) ||GTK_WIDGET_VISIBLE (widget))
      gtk_widget_hide (widget);
  else
      gtk_widget_show (widget);
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.midi_in_controls = GTK_WIDGET_VISIBLE (widget);
}
/**
 *  Function to toggle whether entry toolbar is visible 
 *  
 * 
 */
static void
toggle_entry_toolbar (GtkAction * action, gpointer param) {
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/EntryToolBar");
  if ((!action) ||GTK_WIDGET_VISIBLE (widget))
      gtk_widget_hide (widget);
  else
      gtk_widget_show (widget);
}

/**
 *  Function to toggle whether keyboard bindings can be set by pressing key over menu item 
 *  
 *  
 */
static void
toggle_quick_edits (GtkAction * action, gpointer param)
{
  Denemo.prefs.quickshortcuts = !Denemo.prefs.quickshortcuts;
}



static void
toggle_main_menu (GtkAction * action, gpointer param) {
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/MainMenu");
  if ((!action) || GTK_WIDGET_VISIBLE (widget))
      gtk_widget_hide (widget);
  else
    gtk_widget_show (widget);
}
/**
 *  Function to toggle whether action menubar is visible 
 *  
 *  
 */
static void
toggle_action_menu (GtkAction * action, gpointer param)
{
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ActionMenu");
  if(!widget) return;// internal error - out of step with menu_entries...
  if ((!action) || GTK_WIDGET_VISIBLE (widget))
    {
 
      gtk_widget_hide (widget);
    }
  else
    {
      gtk_widget_show (widget);
    }
}

/**
 *  Function to toggle visibility of print preview pane of current gui
 *  
 *  
 */
static void
toggle_print_view (GtkAction *action, gpointer param)
{
  GtkWidget *w =  gtk_widget_get_toplevel(Denemo.printarea);
  if((!action) || GTK_WIDGET_VISIBLE(w))
    gtk_widget_hide(w);
  else {
    gtk_widget_show(w);
    if(((gint)g_object_get_data(G_OBJECT(Denemo.printarea), "printviewupdate"))<Denemo.gui->changecount)
      refresh_print_view(TRUE);
  }
  return;
}

/**
 *  Function to toggle visibility of lyrics view pane of current movement
 *  
 *  
 */
void
toggle_lyrics_view (GtkAction *action, gpointer param)
{
  GtkWidget *widget = Denemo.gui->si->lyricsbox;
  if(!widget)
    g_warning("No lyrics");
  else {
    if((!action) || GTK_WIDGET_VISIBLE(widget))
      gtk_widget_hide(widget);
    else {
      gtk_widget_show(widget);
    }
    if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
      Denemo.prefs.lyrics_pane = GTK_WIDGET_VISIBLE (widget);
  }
  return;
}

/**
 *  Function to toggle visibility of console view pane
 *  
 *  
 */
static void
toggle_console_view (GtkAction *action, gpointer param)
{
  GtkWidget *widget = gtk_widget_get_parent(Denemo.console);
  if(!widget)
    g_warning("Internal Error");
  else {
    if((!action) || GTK_WIDGET_VISIBLE(widget))
      gtk_widget_hide(widget);
    else {
      gtk_widget_show(widget);
      GtkTextBuffer *buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (Denemo.console));
      GtkTextIter iter;
      /* get end iter */
      gtk_text_buffer_get_end_iter (buffer, &iter);
      /* scroll to end iter */
      gtk_text_view_scroll_to_iter (GTK_TEXT_VIEW (Denemo.console),
                                      &iter, 0.0, FALSE, 0, 0); 
    }
  }
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.console_pane = GTK_WIDGET_VISIBLE (widget);
  return;
}


/**
 *  Function to toggle visibility of print preview pane of current gui
 *  
 *  
 */
void
toggle_score_view (GtkAction *action, gpointer param)
{
  GtkWidget *w = gtk_widget_get_parent(gtk_widget_get_parent(Denemo.scorearea));
  if((!action) || GTK_WIDGET_VISIBLE(w))
    gtk_widget_hide(w);
  else {
    gtk_widget_show(w);
    gtk_widget_grab_focus(Denemo.scorearea);
  }
  return;
}
/**
 *  Function to toggle visibility of titles etc of current gui
 *  
 *  
 */
static void
toggle_scoretitles (GtkAction *action, gpointer param)
{
  GtkWidget *widget = Denemo.gui->buttonboxes;
  if((!action) || GTK_WIDGET_VISIBLE(widget))
    gtk_widget_hide(widget);
  else
    gtk_widget_show(widget);
  if(Denemo.prefs.persistence && (Denemo.gui->view==DENEMO_MENU_VIEW))
    Denemo.prefs.visible_directive_buttons = GTK_WIDGET_VISIBLE (widget);

  return;
}
/**
 *  Function to toggle whether object menubar is visible 
 *  
 *  
 */
static void
toggle_object_menu (GtkAction * action, gpointer param)
{
  GtkWidget *widget;
  widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ObjectMenu");
  if(!widget) return;// internal error - out of step with menu_entries...
  if ((!action) || GTK_WIDGET_VISIBLE (widget))
    {
 
      gtk_widget_hide (widget);
    }
  else
    {
      gtk_widget_show (widget);
    }
}



/**
 * Toggle entries for the menus
 */
GtkToggleActionEntry toggle_menu_entries[] = {
  {ToggleToolbar_STRING, NULL, N_("General Tools"), NULL, N_("Show/hide a toolbar for general operations on music files"),
   G_CALLBACK (toggle_toolbar), TRUE}
  ,
  {TogglePlaybackControls_STRING, NULL, N_("Playback Control"), NULL, N_("Show/hide playback controls"),
   G_CALLBACK (toggle_playback_controls), TRUE}
  ,
  {ToggleMidiInControls_STRING, NULL, N_("Midi In Control"), NULL, N_("Show/hide Midi Input controls"),
   G_CALLBACK (toggle_midi_in_controls), TRUE}
  ,
  {ToggleRhythmToolbar_STRING, NULL, N_("Music Snippets"), NULL, N_("Show/hide a toolbar which allows\nyou to store and enter snippets of music and to enter notes using rhythm pattern of a snippet"),
   G_CALLBACK (toggle_rhythm_toolbar), TRUE}
  ,
  {ToggleEntryToolbar_STRING, NULL, N_("Note and Rest Entry"), NULL, N_("Show/hide a toolbar which allows\nyou to enter notes and rests using the mouse"),
   G_CALLBACK (toggle_entry_toolbar), TRUE}
  ,
  {ToggleObjectMenu_STRING, NULL, N_("Menu of objects"), NULL, N_("Show/hide a menu which is arranged by objects\nThe actions available for note objects change with the mode"),
   G_CALLBACK (toggle_object_menu), TRUE}
  ,
  {ToggleLilyText_STRING, NULL, N_("Show LilyPond"), NULL, N_("Show/hide the LilyPond music typesetting language window"),
   G_CALLBACK (toggle_lilytext), FALSE}
  ,
  {ToggleScript_STRING, NULL, N_("Show Scheme Script"), NULL, N_("Show scheme script window"),
   G_CALLBACK (toggle_scheme), FALSE}
  ,

  {ToggleArticulationPalette_STRING, NULL, N_("_Articulation Palette"), NULL, NULL,
   G_CALLBACK (toggle_articulation_palette), FALSE},

  {TogglePrintView_STRING, NULL, N_("Print View"), NULL, NULL,
   G_CALLBACK (toggle_print_view), FALSE},

  {ToggleLyricsView_STRING, NULL, N_("Lyrics View"), NULL, NULL,
   G_CALLBACK (toggle_lyrics_view), TRUE},

  {ToggleConsoleView_STRING, NULL, N_("Console"), NULL, NULL,
   G_CALLBACK (toggle_console_view), TRUE},

  {ToggleScoreView_STRING, NULL, N_("Score View"), NULL, NULL,
   G_CALLBACK (toggle_score_view), TRUE},
  {ToggleScoreTitles_STRING, NULL, N_("Score Titles, Controls etc"), NULL, NULL,
   G_CALLBACK (toggle_scoretitles), FALSE},


  {QuickEdits_STRING, NULL, N_("Allow Quick Shortcut Edits"), NULL, "Enable editing keybindings by pressing a key while hovering over the menu item",
   G_CALLBACK (toggle_quick_edits), TRUE},
  {RecordScript_STRING, NULL, N_("Record Scheme Script"), NULL, "Start recording menu clicks into the Scheme script text window",
   G_CALLBACK (toggle_record_script), FALSE},
 
  {RHYTHM_E_STRING, NULL, N_("Audible Feedback\nInsert Duration/Edit Note"), NULL, N_("Gives feedback as you enter durations. N.B. durations are entered in Edit mode"),
   G_CALLBACK (toggle_rhythm_mode), FALSE},
  {ReadOnly_STRING, NULL, N_("Read Only"), NULL, "Make score read only\nNot working",
   G_CALLBACK (default_mode), FALSE}
};

/**
 * Radio entries for the modes and entry types
 */
static GtkRadioActionEntry mode_menu_entries[] = {
  {MODELESS_STRING, NULL, N_("No mode"), NULL, "Access all editing functions without change of mode",
   0},
  {CLASSICMODE_STRING, NULL, N_("Classic"), NULL, "The original Denemo note entry mode\nUseful for entering notes into chords\nUse the note names to move the cursor\nUse the durations to insert notes",
   INPUTCLASSIC},
  {INSERTMODE_STRING, NULL, N_("Insert"), NULL, N_("Mode for inserting notes into the score at the cursor position\nUses prevailing duration/rhythm\nUse the durations to set the prevailing duration\nUse the note names to insert the note"),
   INPUTINSERT},
  {EDITMODE_STRING, NULL, N_("Edit"), NULL, N_("Mode for changing the note at cursor (name, duration)\nand to enter notes by duration (rhythms)\nUse the durations to insert notes"),
   INPUTEDIT}
};


static GtkRadioActionEntry type_menu_entries[] = {
  {NOTE_E_STRING, NULL, N_("Note"), NULL,  N_("Normal (note) entry"), INPUTNORMAL},
  {REST_E_STRING, NULL, N_("Rest"), NULL,  N_("Entering rests not notes"), INPUTREST},
  {BLANK_E_STRING, NULL, N_("Non printing rests"), NULL,  N_("Enters rests which will not be printed (just take up space)\nUsed for positioning polyphonic voice entries"), INPUTBLANK}
#if 0
,
  {RHYTHM_E_STRING, NULL, N_("Audible Feedback"), NULL, N_("Gives feedback as you enter durations"),  INPUTRHYTHM|INPUTNORMAL}
#endif
};

static GtkRadioActionEntry input_menu_entries[] = {
  {"KeyboardOnly", NULL, N_("No External Input"), NULL, N_("Entry of notes via computer keyboard only"),
  INPUTKEYBOARD}
  ,
  {"Microphone", NULL, N_("Audio Input"), NULL, N_("Enable pitch entry from microphone"), INPUTAUDIO
   /*  G_CALLBACK (toggle_pitch_recognition), FALSE*/}
  ,
  {"JackMidi", NULL, N_("Midi Input"), NULL,N_("Input of midi via Jack Audio Connection Kit"), INPUTMIDI/*G_CALLBACK (jackmidi)*/}
};

struct cbdata
{
  DenemoGUI *gui;
  gchar *filename;
};

/**
 * Callback for the history menu
 * opens the selected file
 */
static void
openrecent (GtkWidget * widget, gchar *filename)
{
  DenemoGUI *gui = Denemo.gui;
  if (!gui->notsaved || (gui->notsaved && confirmbox (gui)))
    {
      // deletescore(NULL, gui);
      if(open_for_real (filename, gui, FALSE, FALSE))
	{
	  gchar *warning = g_strdup_printf("Load of recently used file %s failed", filename);
	  warningdialog(warning);
	  g_free(warning);
	}
    }
}

 
/**
 * Add history entry to the History menu, create a menu item for it
 */
void
addhistorymenuitem (gchar *filename)
{
  GList *g;
  if(!g_file_test(filename,  G_FILE_TEST_EXISTS))
    return;
  GtkWidget *item =
    gtk_ui_manager_get_widget (Denemo.ui_manager,
			       "/MainMenu/FileMenu/OpenRecent/Stub");
  GtkWidget *menu = gtk_widget_get_parent (GTK_WIDGET (item));
  
  item = gtk_menu_item_new_with_label (filename);
  gtk_menu_shell_insert (GTK_MENU_SHELL (menu), item, 0);
  g_signal_connect (G_OBJECT(item), "activate", G_CALLBACK (openrecent), g_strdup(filename));
  gtk_widget_show (item);
}

/**
 * Top-Level function to populate the History menu
 * with elements read from the denemohistory file
 */
static void
populate_opened_recent (void)
{
  g_queue_foreach (Denemo.prefs.history, (GFunc)addhistorymenuitem, NULL);
}

static 	void show_type(GtkWidget *widget, gchar *message) {
    g_print("%s%s\n",message, widget?g_type_name(G_TYPE_FROM_INSTANCE(widget)):"NULL widget");
  }
/* set all labels in the hierarchy below widget to use markup */
static void use_markup(GtkWidget *widget)
{
  if (!widget)
	return;
  //show_type(widget, "Widget Type: ");

 
  //g_print("container type %x\n", GTK_IS_CONTAINER(widget));
  //g_print("label type %x\n", GTK_IS_LABEL(widget));
  //g_print("menu item type %x\n",GTK_IS_MENU_ITEM(widget));
  //g_print("tool item type %x\n",GTK_IS_TOOL_ITEM(widget));
  //g_print("descended to use markup on %p\n", widget);

  if(GTK_IS_LABEL(widget)) {
   // gtk_label_set_use_underline (GTK_LABEL (widget), FALSE); font_desc gets interpreted in GtkLabel but not GtkAccelLabel hmmm...
    //g_print("Before we have %d\n", gtk_label_get_use_markup        (widget));
    //gchar * label = gtk_label_get_label(widget);
     //g_print("label before is \"%s\"\n", label);
    
    gtk_label_set_use_markup (GTK_LABEL (widget), TRUE);
    //g_print("after we have %d\n", gtk_label_get_use_markup        (widget));
    //if(*label=='M')
    //g_print("seting %p", widget),gtk_label_set_markup(widget, "hello"MUSIC_FONT("33")"ok"), show_type(widget, "should be label: "), label = gtk_label_get_label(widget),g_print("label now %s\n",label) ;

  }
  else
 if(GTK_IS_CONTAINER(widget)) {
    GList *g = gtk_container_get_children (GTK_CONTAINER(widget));
    for(;g;g=g->next)
      use_markup(g->data);
    if (GTK_IS_MENU_ITEM(widget)) {
      use_markup(gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)));
    }
 }
}



/**
 * Key snooper function. This function intercepts all key events before they are
 * passed to other functions for further processing. We use do quick shortcut edits.
 */
static gint dnm_key_snooper(GtkWidget *grab_widget, GdkEventKey *event)
{
    //no special processing for key release events
    if (event->type == GDK_KEY_RELEASE)
        return FALSE;
    //if the grab_widget is a menu, the event could be a quick edit
    if (Denemo.prefs.quickshortcuts && GTK_IS_MENU (grab_widget)) {
        return keymap_accel_quick_edit_snooper(grab_widget, event);
    }
    //else we let the event be processed by other functions
    return FALSE;
}


static void
switch_page (GtkNotebook *notebook, GtkNotebookPage *page,  guint pagenum) {
  //g_print("switching pagenum %d\n",pagenum);
  DenemoGUI *gui = Denemo.gui;
  if(gui==NULL)
    return;
  GList *g = g_list_nth(Denemo.guis, pagenum);
  if(g==NULL) {
    g_warning("got a switch page, but there is no such page in Denemo.guis\n");
    return;
  }
  DenemoGUI *newgui = g->data;
  if(gui==newgui)
    return;//on arrival Denemo.gui is already set to the new gui when you are doing new window
  /* turn off the LilyPond window if it is on
   it would be nice to keep a record of whether it was open for re-opening
   on return to this tab FIXME*/
  {
    GtkWidget *widget;
    widget = gtk_ui_manager_get_widget (Denemo.ui_manager, "/MainMenu/ViewMenu/ToggleLilyText");
    if(gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM (widget)))
      gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (widget), FALSE);
  }
  unhighlight_rhythm(Denemo.gui->prevailing_rhythm);
  Denemo.gui = gui = (DenemoGUI*)(g->data);
     g_print("switch page\n");


  if(Denemo.prefs.visible_directive_buttons) {
    gtk_widget_hide(Denemo.gui->buttonboxes);
    activate_action("/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);
  }
  switch(gui->mode & ~MODE_MASK ) {
    case INPUTINSERT:
      activate_action( "/MainMenu/ModeMenu/InsertMode");
      break;
    case INPUTEDIT:
      activate_action( "/MainMenu/ModeMenu/EditMode");
      break;
    case INPUTCLASSIC:
      activate_action( "/MainMenu/ModeMenu/ClassicMode");
      break;
    case 0:
      activate_action( "/MainMenu/ModeMenu/Modeless");
      break;
    default:
      ;
    }

  switch(gui->mode & ~ENTRY_TYPE_MASK ) {
    case INPUTNORMAL:
      activate_action( "/MainMenu/ModeMenu/Note");
      break;
    case INPUTBLANK:
      activate_action( "/MainMenu/ModeMenu/Blank");
      break;
    case INPUTREST:
      activate_action( "/MainMenu/ModeMenu/Rest");
      break;
    case INPUTRHYTHM:
      g_print("activating rhythm\n");
      activate_action( "/MainMenu/ModeMenu/Rhythm");
      break;

    default:
      ;
    }
  set_title_bar(Denemo.gui);
  highlight_rhythm(Denemo.gui->prevailing_rhythm);
  gtk_widget_queue_draw(Denemo.scorearea);
}




static gboolean  thecallback      (GtkWidget      *widget,
                                            GdkEventButton *event,
				   GtkAction *action) {
  if (event->button==1 && !(event->state&(GDK_SHIFT_MASK|GDK_CONTROL_MASK)))
    return FALSE;
  g_print("going for %d for %d\n", event->button, event->state);
  event->button = 3;
  return menu_click(widget, event, action);
}

/*  proxy_connected
    callback to set callback for right click on menu items and
    set the shortcut label 

*/
static void  proxy_connected (GtkUIManager *uimanager, GtkAction *action, GtkWidget    *proxy) {
  int command_idx;

  attach_right_click_callback(proxy, action);

  if(GTK_IS_IMAGE_MENU_ITEM(proxy)) {
    //  ????????????? should I put an icon named for the action->label into an icon factory here (we could just have one, static, and use gtk_icon_factory_add_default??????????
    if(!g_object_get_data(G_OBJECT(action), "connected"))
    g_signal_connect(G_OBJECT(proxy), "button-press-event", G_CALLBACK(thecallback), action);
     g_object_set_data(G_OBJECT(action), "connected", (gpointer)1);  //Unfortunately GtkImageMenuItems that pop up a menu do not wait for a button press - the focus switches to the popped up memory on entry. So we don't see this signal for them
  }
#if (GTK_MINOR_VERSION <10)
       attach_action_to_widget(proxy, action, Denemo.gui);
#endif
  if(Denemo.map==NULL)
     return;
  command_idx = lookup_command_from_name(Denemo.map,
				       gtk_action_get_name(action));

    
  if (command_idx != -1) 
    update_accel_labels(Denemo.map, command_idx);
  //  else //not an error, it occurs for menus being loaded
  //   g_warning("%s is not yet in map\n",  gtk_action_get_name(action));
  gboolean hidden= (gboolean) (action?g_object_get_data(G_OBJECT(action), "hidden"):NULL);
  if(hidden) {
	    set_visibility_for_action(action, FALSE);	   
	  }
}



static void create_console(GtkBox *box) {
  //GtkWidget *vpaned = gtk_vpaned_new ();
  //gtk_container_set_border_width (GTK_CONTAINER(vpaned), 5);
  //gtk_box_pack_start (GTK_BOX (box), vpaned, FALSE, TRUE, 0);
  Denemo.console = gtk_text_view_new ();
  GtkWidget *sw = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
				  GTK_POLICY_AUTOMATIC,
				  GTK_POLICY_AUTOMATIC);
  //gtk_paned_add1 (GTK_PANED (vpaned), sw);
gtk_box_pack_start (GTK_BOX (box), sw, FALSE, TRUE, 0);
  gtk_container_add (GTK_CONTAINER (sw), Denemo.console);
  // gtk_widget_show_all(vpaned);
 gtk_widget_show_all(sw);
}

GtkWidget* create_playbutton(GtkWidget *box, gchar *thelabel, gpointer callback, gchar *image) {
  GtkWidget *button;
  if (thelabel)
    button = gtk_button_new_with_label(thelabel);
  else 
    button = gtk_button_new();
  GTK_WIDGET_UNSET_FLAGS(button, GTK_CAN_FOCUS);
  if (image){ 
    gtk_button_set_image (GTK_BUTTON(button), 
			  gtk_image_new_from_stock(image, GTK_ICON_SIZE_BUTTON));
  }									
  g_signal_connect(button, "clicked", G_CALLBACK(callback), NULL);
  gtk_box_pack_start (GTK_BOX(box), button, FALSE, TRUE, 0);
  return button;
}

void toggle_playbutton(void) {
  static gboolean pause = TRUE;
  if(pause) {
    gtk_button_set_image (GTK_BUTTON(playbutton), 
			  gtk_image_new_from_stock(GTK_STOCK_MEDIA_PAUSE, GTK_ICON_SIZE_BUTTON));
  } else {
    gtk_button_set_image (GTK_BUTTON(playbutton), 
			  gtk_image_new_from_stock(GTK_STOCK_MEDIA_PLAY, GTK_ICON_SIZE_BUTTON));
 }
  pause = !pause;
}

//Set the master volume of the passed score and change the slider to suit
void set_master_volume(DenemoScore *si, gdouble volume) {
  si->master_volume = volume;
  if(master_vol_adj) {
    master_vol_adj->value = volume;
    gtk_adjustment_changed(master_vol_adj);
  }
}

//Set the master tempo of the passed score and change the slider to suit
void set_master_tempo(DenemoScore *si, gdouble tempo) {
  si->master_tempo = tempo;
  if(master_tempo_adj) {
    master_tempo_adj->value = tempo * si->tempo;
    gtk_adjustment_changed(master_tempo_adj);
  }
}

/* create_window() creates the toplevel window and all the menus - it only
   called once per invocation of Denemo */
static void
create_window(void) {
  GtkWidget *main_vbox, *menubar, *toolbar, *hbox;
  GtkActionGroup *action_group;
  GtkUIManager *ui_manager;
  GtkAccelGroup *accel_group;
  GError *error;
  GtkWidget *widget;
  gchar *data_file;

  Denemo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (Denemo.window), "Denemo Main Window");
  loadWindowState(/* it accesses Denemo.window */);
#ifdef G_OS_WIN32
  data_file = g_build_filename (get_data_dir (), "icons","denemo.png", NULL);
#else
  data_file = g_strconcat (get_data_dir (), "/../pixmaps/denemo.png", NULL);//FIXME installed in wrong place?
#endif
  gtk_window_set_default_icon_from_file (data_file, NULL);
  gtk_signal_connect (GTK_OBJECT (Denemo.window), "delete_event",
		      (GtkSignalFunc) delete_callback, NULL);
  g_free (data_file);

  gtk_window_set_resizable (GTK_WINDOW (Denemo.window), TRUE);

  //create_scheme_window();






  main_vbox = gtk_vbox_new (FALSE, 1);
  gtk_container_border_width (GTK_CONTAINER (main_vbox), 1);
  gtk_container_add (GTK_CONTAINER (Denemo.window), main_vbox);
  gtk_widget_show (main_vbox);

  Denemo.action_group = action_group = gtk_action_group_new ("MenuActions");
  gtk_action_group_set_translation_domain (action_group, NULL); 
  /* This also sets current Denemo.gui as the  callback data for all the functions in the
   * menubar, which is not needed since we have only one set of actions for all
   the guis. We will always act on Denemo.gui anyway.*/
  gtk_action_group_add_actions (action_group, menu_entries,
  			G_N_ELEMENTS (menu_entries),  Denemo.gui);
  gtk_action_group_add_toggle_actions (action_group,
				       toggle_menu_entries,
				       G_N_ELEMENTS (toggle_menu_entries),
				       Denemo.gui);
  gtk_action_group_add_radio_actions (action_group,
				       mode_menu_entries,
				       G_N_ELEMENTS (mode_menu_entries),
				      INPUTINSERT/* initial value */, 
				      G_CALLBACK(change_mode),  Denemo.gui);


  gtk_action_group_add_radio_actions (action_group,
				       type_menu_entries,
				       G_N_ELEMENTS (type_menu_entries),
				      INPUTNORMAL/* initial value */, 
				      G_CALLBACK(change_entry_type),  Denemo.gui);

  gtk_action_group_add_radio_actions (action_group,
				       input_menu_entries,
				       G_N_ELEMENTS (input_menu_entries),
				      INPUTKEYBOARD/* initial value */, 
				      G_CALLBACK(change_input_type),  NULL);




  ui_manager = gtk_ui_manager_new ();
  Denemo.ui_manager = ui_manager;
  gtk_ui_manager_set_add_tearoffs (Denemo.ui_manager, TRUE);
  gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);

  g_signal_connect(G_OBJECT(Denemo.ui_manager), "connect-proxy", G_CALLBACK(proxy_connected), NULL);


  //We do not use accel_group anymore TODO delete the next 2 lines
  //accel_group = gtk_ui_manager_get_accel_group (ui_manager);
  //gtk_window_add_accel_group (GTK_WINDOW (Denemo.window), accel_group);

  /* TODO Lily_menu actions are handled differently for the time being
   * What are these actions?
   */
  GtkActionEntry lily_menus[] = {
    {"LilyToggleShow", NULL, N_("Show/Hide"),NULL, N_("Toggle visibility of section"),G_CALLBACK (toggle_lily_visible_cb)},
    {"LilyCreateCustom", NULL, N_("Create Custom Version"),NULL, N_("Create a custom version of this block"),G_CALLBACK (custom_lily_cb)},
    {"LilyDelete", NULL, N_("Delete Block"),NULL, N_("Delete this block"),G_CALLBACK (delete_lily_cb)}
  };

  {
  GtkActionGroup *lilyaction_group = gtk_action_group_new ("LilyActions");
  gtk_action_group_set_translation_domain (lilyaction_group, NULL); 
  gtk_action_group_add_actions (lilyaction_group, lily_menus,
				G_N_ELEMENTS (lily_menus), Denemo.gui);
  gtk_ui_manager_insert_action_group (ui_manager, lilyaction_group, 1);
  }
  data_file = g_build_filename (
#ifndef USE_LOCAL_DENEMOUI
get_data_dir (),
#endif
 "denemoui.xml", NULL);
  error = NULL;
  if (!gtk_ui_manager_add_ui_from_file (ui_manager, data_file, &error))
    {
      g_message ("building menu failed: %s", error->message);
      g_error_free (error);
      gchar *message = g_strdup_printf("The denemoui.xml %s file could not be used - exiting", data_file);
      warningdialog(message);
      exit (EXIT_FAILURE);
    }
  g_free (data_file);


  {//pops up with menu items for the directives attached to the current note
    GtkWidget *menu = gtk_ui_manager_get_widget (Denemo.ui_manager, "/NoteEditPopup");
    g_signal_connect(menu, "deactivate", G_CALLBACK(unpopulate_menu), NULL);
  }

  //menubar = gtk_item_factory_get_widget (item_factory, "<main>");
  Denemo.menubar = gtk_ui_manager_get_widget (ui_manager, "/MainMenu");// this triggers Lily... missing action
  gtk_box_pack_start (GTK_BOX (main_vbox), Denemo.menubar, FALSE, TRUE, 0);
  gtk_widget_show (Denemo.menubar);

  toolbar = gtk_ui_manager_get_widget (ui_manager, "/ToolBar");
  // The user should be able to decide toolbar style.
  // But without gnome, there is no (ui) to set this option.

  gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_BOTH_HORIZ);
  gtk_box_pack_start (GTK_BOX (main_vbox), toolbar, FALSE, TRUE, 0);
  GTK_WIDGET_UNSET_FLAGS(toolbar, GTK_CAN_FOCUS); 


  {
    Denemo.playback_control = gtk_vbox_new(FALSE, 1);
    gtk_box_pack_start (GTK_BOX (main_vbox), Denemo.playback_control, FALSE, TRUE, 0);
    GtkFrame *frame= (GtkFrame *)gtk_frame_new(_("Playback Control"));
    gtk_frame_set_shadow_type((GtkFrame *)frame, GTK_SHADOW_IN);
    gtk_container_add (GTK_CONTAINER (Denemo.playback_control), GTK_WIDGET(frame));

    GtkWidget *inner1 = gtk_vbox_new(FALSE, 1);
    gtk_container_add (GTK_CONTAINER (frame), inner1);


    GtkWidget *inner = gtk_hbox_new(FALSE, 1);
    gtk_box_pack_start (GTK_BOX (inner1), inner, FALSE, TRUE, 0);

    //gtk_box_pack_start (GTK_BOX (main_vbox), inner, FALSE, TRUE, 0);
    GTK_WIDGET_UNSET_FLAGS(inner, GTK_CAN_FOCUS);
    GtkWidget *button;
    GtkWidget *label;


    //create_playbutton(inner, NULL, pb_first, GTK_STOCK_GOTO_FIRST);
   

    
    //create_playbutton(inner,NULL, pb_rewind, GTK_STOCK_MEDIA_REWIND);

    create_playbutton(inner,NULL, pb_go_back, GTK_STOCK_GO_BACK);
    create_playbutton(inner,NULL, pb_start_to_cursor, GTK_STOCK_GO_DOWN);
    create_playbutton(inner,NULL, pb_next, GTK_STOCK_GO_FORWARD );
    create_playbutton(inner,NULL, pb_stop, GTK_STOCK_MEDIA_STOP);
    playbutton = create_playbutton(inner,NULL, pb_play, GTK_STOCK_MEDIA_PLAY);
    recordbutton = create_playbutton(inner,NULL, pb_record,  GTK_STOCK_MEDIA_RECORD);
    create_playbutton(inner,NULL, pb_previous, GTK_STOCK_GO_BACK);
    create_playbutton(inner,NULL, pb_end_to_cursor, GTK_STOCK_GO_UP);
   
    create_playbutton(inner,NULL, pb_go_forward, GTK_STOCK_GO_FORWARD);

    //create_playbutton(inner,NULL, pb_forward, GTK_STOCK_MEDIA_FORWARD);
 
    create_playbutton(inner,"Loop", pb_loop, NULL);
    
   
    create_playbutton(inner,
#ifdef _HAVE_JACK_
"Panic"
#else
"Reset"
#endif
, pb_panic, NULL);


      create_playbutton(inner, "Set From Selection", pb_set_range, NULL);
      create_playbutton(inner, "Playback Range", pb_range, NULL);
    GtkWidget *temperament_control = get_temperament_combo();
    if(!gtk_widget_get_parent(temperament_control))
      //gtk_container_add (GTK_CONTAINER (inner), temperament_control);
      gtk_box_pack_start (GTK_BOX (inner), temperament_control, FALSE, FALSE, 0);
    {GtkWidget *hbox;
      hbox = gtk_hbox_new(FALSE, 1);
      gtk_box_pack_start (GTK_BOX (inner1), hbox, TRUE, TRUE, 0);
      /* Tempo */
      label = gtk_label_new (_("Tempo:"));
      GTK_WIDGET_UNSET_FLAGS(label, GTK_CAN_FOCUS);
      gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
      master_tempo_adj = (GtkAdjustment*)gtk_adjustment_new (120.0, 0.0, 600.0, 1.0, 1.0, 0.0);
      GtkWidget *hscale = gtk_hscale_new(GTK_ADJUSTMENT( master_tempo_adj));
      gtk_scale_set_digits (GTK_SCALE(hscale), 0);
      GTK_WIDGET_UNSET_FLAGS(hscale, GTK_CAN_FOCUS);

      g_signal_connect(GTK_OBJECT(master_tempo_adj), "value_changed", GTK_SIGNAL_FUNC(pb_tempo), NULL);
      gtk_box_pack_start (GTK_BOX (hbox), hscale, TRUE, TRUE, 0);

      //create_playbutton(hbox, "Set Tempo", pb_set_tempo, NULL);

      /* Volume */
      label = gtk_label_new (_("Volume"));
      GTK_WIDGET_UNSET_FLAGS(label, GTK_CAN_FOCUS);
      gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);

      master_vol_adj = (GtkAdjustment *)gtk_adjustment_new (1.0, 0.0, 1.0, 1.0, 1.0, 0.0);

      hscale = gtk_hscale_new(GTK_ADJUSTMENT( master_vol_adj));
      gtk_scale_set_digits (GTK_SCALE(hscale), 2);
      GTK_WIDGET_UNSET_FLAGS(hscale, GTK_CAN_FOCUS);
      g_signal_connect(G_OBJECT( master_vol_adj), "value_changed", GTK_SIGNAL_FUNC(pb_volume), NULL);
      gtk_box_pack_start (GTK_BOX (hbox), hscale, TRUE, TRUE, 0);

    }


    Denemo.midi_in_control = gtk_vbox_new(FALSE, 1);
    gtk_box_pack_start (GTK_BOX (main_vbox), Denemo.midi_in_control, FALSE, TRUE, 0);
    frame= (GtkFrame *)gtk_frame_new(_("Midi In Control"));
    gtk_frame_set_shadow_type((GtkFrame *)frame, GTK_SHADOW_IN);
    gtk_container_add (GTK_CONTAINER (Denemo.midi_in_control), GTK_WIDGET(frame));
    inner1 = gtk_vbox_new(FALSE, 1);
    gtk_container_add (GTK_CONTAINER (frame), inner1);
    inner = gtk_hbox_new(FALSE, 1);
    gtk_box_pack_start (GTK_BOX (inner1), inner, FALSE, TRUE, 0);
    GtkWidget *enharmonic_control = get_enharmonic_frame();
    if(!gtk_widget_get_parent(enharmonic_control))
      gtk_container_add (GTK_CONTAINER (inner1), enharmonic_control);

    {GtkWidget *hbox;
      hbox = gtk_hbox_new(FALSE, 1);
      gtk_box_pack_start (GTK_BOX (inner1), hbox, TRUE, TRUE, 0);
      midithrubutton = create_playbutton(hbox, _("MIDI in -> Score"), pb_midi_thru, NULL);
      deletebutton = create_playbutton(hbox, "Delete", pb_midi_delete, NULL);
      convertbutton = create_playbutton(hbox, "Convert", pb_midi_convert, NULL);
      gtk_widget_show_all (Denemo.midi_in_control);
      gtk_widget_show_all (Denemo.playback_control);
      gtk_widget_hide(deletebutton);
      gtk_widget_hide(convertbutton);
      }
  }


  toolbar = gtk_ui_manager_get_widget (ui_manager, "/EntryToolBar");
  //g_print("EntryToolbar is %p\n", toolbar);
  gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_TEXT);
  gtk_box_pack_start (GTK_BOX (main_vbox), toolbar, FALSE, TRUE, 0);
  GTK_WIDGET_UNSET_FLAGS(toolbar, GTK_CAN_FOCUS);

  // gtk_widget_show (toolbar); cannot show this until the GtkLabels have become GtkAccelLabels - a gtk bug

  toolbar = gtk_ui_manager_get_widget (ui_manager, "/RhythmToolBar");
  gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_TEXT);
  gtk_box_pack_start (GTK_BOX (main_vbox), toolbar, FALSE, TRUE, 0);

  menubar = gtk_ui_manager_get_widget (ui_manager, "/ObjectMenu");
  if(menubar) {
    gtk_box_pack_start (GTK_BOX (main_vbox), menubar, FALSE, TRUE, 0);
  }


  //  menubar = gtk_ui_manager_get_widget (ui_manager, "/ActionMenu");
  //  if(menubar) {
  //    gtk_box_pack_start (GTK_BOX (main_vbox), menubar, FALSE, TRUE, 0);
  //  }

  Denemo.notebook = gtk_notebook_new ();
  gtk_notebook_set_show_tabs (GTK_NOTEBOOK(Denemo.notebook), FALSE);//only show when more than one
  //gtk_notebook_popup_enable (Denemo.notebook);?? doesn't work...
  gtk_widget_show (Denemo.notebook);
  gtk_box_pack_start (GTK_BOX (main_vbox), Denemo.notebook, FALSE, FALSE, 0);

 {
  Denemo.scorearea = gtk_drawing_area_new ();
  GtkWidget *scorearea_topbox = gtk_vbox_new(FALSE, 1);
  gtk_box_pack_start (GTK_BOX (main_vbox), scorearea_topbox, TRUE, TRUE,
		      0);
  GtkWidget *score_and_scroll_hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (scorearea_topbox), score_and_scroll_hbox, TRUE, TRUE,
		      0);
  gtk_widget_show (score_and_scroll_hbox);

  gtk_box_pack_start (GTK_BOX (score_and_scroll_hbox), Denemo.scorearea, TRUE,
		      TRUE, 0);// with this, the scorearea_expose_event is called
  gtk_widget_show (Denemo.scorearea);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "expose_event",
		      G_CALLBACK (scorearea_expose_event), NULL);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "configure_event",
		      G_CALLBACK (scorearea_configure_event), NULL);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "button_release_event",
		      G_CALLBACK (scorearea_button_release), NULL);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "motion_notify_event",
		      G_CALLBACK (scorearea_motion_notify), NULL);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "leave-notify-event",
			       G_CALLBACK (scorearea_leave_event), NULL);
  gtk_signal_connect (GTK_OBJECT (Denemo.scorearea), "scroll_event",
		      (GtkSignalFunc) scorearea_scroll_event, NULL);
  //g_signal_handlers_block_by_func(Denemo.scorearea, G_CALLBACK (scorearea_motion_notify), NULL);
  g_signal_connect (G_OBJECT (Denemo.scorearea), "button_press_event",
		      G_CALLBACK (scorearea_button_press), NULL);
  gtk_signal_connect (GTK_OBJECT (Denemo.scorearea), "key_press_event",
		      (GtkSignalFunc) scorearea_keypress_event, NULL);
  gtk_signal_connect (GTK_OBJECT (Denemo.scorearea), "key_release_event",
		      (GtkSignalFunc) scorearea_keyrelease_event, NULL);



  gtk_widget_add_events/*gtk_widget_set_events*/ (Denemo.scorearea, (GDK_EXPOSURE_MASK
					  | GDK_POINTER_MOTION_MASK
					  | GDK_LEAVE_NOTIFY_MASK
					  | GDK_BUTTON_PRESS_MASK
					  | GDK_BUTTON_RELEASE_MASK));

  Denemo.vadjustment = gtk_adjustment_new (1.0, 1.0, 2.0, 1.0, 4.0, 1.0);
  gtk_signal_connect (GTK_OBJECT (Denemo.vadjustment), "value_changed",
		      GTK_SIGNAL_FUNC (vertical_scroll), NULL);
  Denemo.vscrollbar = gtk_vscrollbar_new (GTK_ADJUSTMENT (Denemo.vadjustment));
  gtk_box_pack_start (GTK_BOX (score_and_scroll_hbox), Denemo.vscrollbar, FALSE,
		      TRUE, 0);
  gtk_widget_show (Denemo.vscrollbar);

  Denemo.hadjustment = gtk_adjustment_new (1.0, 1.0, 2.0, 1.0, 4.0, 1.0);

  gtk_signal_connect (GTK_OBJECT (Denemo.hadjustment), "value_changed",
		      GTK_SIGNAL_FUNC (horizontal_scroll), NULL);
  Denemo.hscrollbar = gtk_hscrollbar_new (GTK_ADJUSTMENT (Denemo.hadjustment));
  gtk_box_pack_start (GTK_BOX (scorearea_topbox), Denemo.hscrollbar, FALSE, TRUE, 0);
  gtk_widget_show_all (scorearea_topbox);
  }



  create_console(GTK_BOX(main_vbox));
  Denemo.statusbar = gtk_statusbar_new ();
  hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), Denemo.statusbar, TRUE, TRUE, 5);
  gtk_widget_show (Denemo.statusbar);
  Denemo.status_context_id =
    gtk_statusbar_get_context_id (GTK_STATUSBAR (Denemo.statusbar), "Denemo");
  gtk_statusbar_push (GTK_STATUSBAR (Denemo.statusbar), Denemo.status_context_id,
		      "Denemo");
  Denemo.input_source = gtk_label_new("No external input");
  Denemo.input_filters = NULL;
  gtk_box_pack_end (GTK_BOX (hbox), Denemo.input_source, TRUE, TRUE, 5);
  gtk_widget_show (hbox);

  create_scheme_window();


  gtk_widget_show(Denemo.window);
  /* Now that the window is shown, initialize the gcs */
  gcs_init (Denemo.window->window);

  data_file = g_build_filename (
#ifndef USE_LOCAL_DENEMOUI
get_data_dir (),
#endif
 "denemoui.xml", NULL);
  parse_paths(data_file, Denemo.gui);
  g_free(data_file);

  use_markup(Denemo.window);/* set all the labels to use markup so that we can use the music font. Be aware this means you cannot use labels involving "&" "<" and ">" and so on without escaping them 
FIXME labels in toolitems are not correct until you do NewWindow.
Really we should change the default for the class.*/
 //  g_print("Turning on the modes\n");


 //write_status(Denemo.gui);
 Denemo.InsertModeMenu = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ObjectMenu/NotesRests/InsertModeNote");
 Denemo.EditModeMenu = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ObjectMenu/NotesRests/EditModeNote");
 Denemo.ClassicModeMenu = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ObjectMenu/NotesRests/ClassicModeNote");
 Denemo.ModelessMenu = gtk_ui_manager_get_widget (Denemo.ui_manager, "/ObjectMenu/NotesRests/ModelessNote");

 //gtk_widget_hide (gtk_ui_manager_get_widget (ui_manager, "/ActionMenu"));// make a prefs thing
 //GTK bug now fixed gtk_widget_hide (gtk_ui_manager_get_widget (ui_manager, "/EntryToolBar")); //otherwise buttons only sensitive around their edges


  g_signal_connect (G_OBJECT(Denemo.notebook), "switch_page", G_CALLBACK(switch_page), NULL);
}   /* create window */


void
newview (GtkAction *action, gpointer param)
{
  newtab(NULL, NULL);
  Denemo.gui->si->undo_guard = 1;//do not collect undo for initialization of score
  load_scheme_init();
  load_initdotdenemo();
  Denemo.gui->si->undo_guard = Denemo.prefs.disable_undo;
}

/**
 * Creates a new DenemoGUI structure represented by a tab in a notebook: the DenemoGUI can, at anyone time, control one musical score possibly of several movements. It can, from time to time have different musical scores loaded into it. So it is to be thought of as a Music Score Editor.
 * This DenemoGUI* gui is appended to the global list Denemo.guis.
 * A single movement (DenemoScore) is instantiated in the gui.
 * 
 */
static void
newtab (GtkAction *action, gpointer param) {
  static gint id=1;
  //  if(Denemo.guis==NULL)
  //    action_group = create_window();
  DenemoGUI *gui = (DenemoGUI *) g_malloc0 (sizeof (DenemoGUI));
  gui->id = id++;//uniquely identifies this musical score editor for duration of program.
  gui->mode = Denemo.prefs.mode;
  Denemo.guis = g_list_append (Denemo.guis, gui);


  Denemo.gui = NULL;
  // Denemo.gui = gui; must do this after switching to page, so after creating page
  gui->lilycontrol.papersize = g_string_new ("a4");	//A4 default
  gui->lilycontrol.staffsize = g_string_new("18");
  gui->lilycontrol.lilyversion = g_string_new ("");
  gui->lilycontrol.orientation = TRUE;	//portrait



  //gui->pixmap = NULL;

  /* Initialize the GUI */

  //create the tab for this gui
  GtkWidget *top_vbox = gtk_vbox_new (FALSE, 1);
  gui->buttonboxes = gtk_vbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (top_vbox), gui->buttonboxes, FALSE, TRUE,
		      0);
  gui->buttonbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (gui->buttonboxes), gui->buttonbox, FALSE, TRUE,
		      0);
  GTK_WIDGET_UNSET_FLAGS(gui->buttonboxes, GTK_CAN_FOCUS);
  GTK_WIDGET_UNSET_FLAGS(gui->buttonbox, GTK_CAN_FOCUS);




 
  GtkWidget *main_vbox = gtk_vbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (top_vbox), main_vbox, TRUE, TRUE,
		      0);
  gint pagenum = //gtk_notebook_append_page (GTK_NOTEBOOK (Denemo.notebook), top_vbox, NULL);
  gtk_notebook_insert_page_menu (GTK_NOTEBOOK (Denemo.notebook), top_vbox, NULL, NULL, -1);    
  /*(GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label,
                                                         gint position);*/
  gtk_notebook_popup_enable (GTK_NOTEBOOK (Denemo.notebook));

  Denemo.page = gtk_notebook_get_nth_page (GTK_NOTEBOOK(Denemo.notebook), pagenum);//note Denemo.page is redundant, it is set to the last page created and it is never unset even when that page is deleted - it is only used by the selection paste routine.
  gtk_notebook_set_current_page (GTK_NOTEBOOK(Denemo.notebook), pagenum);
  
  Denemo.gui = gui;
  set_title_bar(gui);
 if(pagenum)
   gtk_notebook_set_show_tabs (GTK_NOTEBOOK(Denemo.notebook), TRUE);
  set_title_bar(gui);
  gtk_widget_show (top_vbox);
  gtk_widget_show (main_vbox);

  //gtk_grab_remove(toolbar);  ?????????

#if 0
  GtkWidget *hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, TRUE, 0);
  gtk_widget_show (hbox);
#endif


  install_printpreview(gui, main_vbox);
 
  //FIXME populate_opened_recent (gui);

  /* create the first movement now because showing the window causes it to try to draw the scorearea
   which it cannot do before there is a score. FIXME use signal blocking to control this - see importxml.c */
  point_to_new_movement (gui);
  gui->movements = g_list_append(NULL, gui->si);
 
  install_lyrics_preview(gui->si, top_vbox);

  gtk_widget_show (Denemo.page);
  gtk_widget_grab_focus (Denemo.scorearea);



 create_rhythm_cb((gpointer)insert_chord_0key, NULL); 
 create_rhythm_cb((gpointer)insert_chord_1key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_2key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_3key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_4key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_5key, NULL); 
 create_rhythm_cb((gpointer)insert_chord_6key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_7key, NULL);   
 create_rhythm_cb((gpointer)insert_chord_8key, NULL);   


 create_rhythm_cb((gpointer)insert_rest_0key, NULL); 
 create_rhythm_cb((gpointer)insert_rest_1key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_2key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_3key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_4key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_5key, NULL); 
 create_rhythm_cb((gpointer)insert_rest_6key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_7key, NULL);   
 create_rhythm_cb((gpointer)insert_rest_8key, NULL);   


  if (Denemo.prefs.articulation_palette)
    toggle_articulation_palette (NULL, NULL);
  //Denemo.gui->mode = Denemo.prefs.mode;

  // this stops the keyboard input from getting to  scorearea_keypress_event if done after attaching the signal, why?
  gtk_notebook_set_current_page (GTK_NOTEBOOK(Denemo.notebook), pagenum);//if this is not done Gdk-CRITICAL **: gdk_draw_drawable: assertion `GDK_IS_DRAWABLE (drawable)' failed message results. Presumably because we have failed to block the (expose_event) drawing while we set up the new page. FIXME.


  GTK_WIDGET_SET_FLAGS(Denemo.scorearea, GTK_CAN_FOCUS);
  gtk_widget_grab_focus (GTK_WIDGET(Denemo.scorearea));

 if (Denemo.prefs.autosave) {
   if(Denemo.autosaveid) {
     g_print("No autosave on new tab");
   }
   else {
     Denemo.autosaveid = g_timeout_add (Denemo.prefs.autosave_timeout * 1000 * 60,
					(GSourceFunc) auto_save_document_timeout, Denemo.gui);
   }
 }


  if(Denemo.prefs.visible_directive_buttons) {
    gtk_widget_hide(Denemo.gui->buttonboxes);
    activate_action("/MainMenu/ViewMenu/"ToggleScoreTitles_STRING);
  }

} /* end of newtab creating a new DenemoGUI holding one musical score */