File: fweelin_core.cc

package info (click to toggle)
freewheeling 0.6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,960 kB
  • sloc: cpp: 22,418; sh: 3,711; xml: 2,879; makefile: 78; ansic: 12
file content (3692 lines) | stat: -rwxr-xr-x 115,704 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
/* 
   Truth has a power like electricity
   When we dance in Truth,
   it is infectious,
   unmistakable. 
*/

/* Copyright 2004-2008 Jan Pekau (JP Mercury) <swirlee@vcn.bc.ca>
   
   This file is part of Freewheeling.
   
   Freewheeling is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   (at your option) any later version.
   
   Freewheeling is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with Freewheeling.  If not, see <http://www.gnu.org/licenses/>. */

#include <sys/stat.h>
#include <sys/time.h>
#include <utime.h>

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

#include <math.h>
#include <string.h>

#include <pthread.h>
#include <sched.h>
#include <sys/mman.h>

#include <X11/Xlib.h>

#include <glob.h>

#include "fweelin_core.h"
#include "fweelin_fluidsynth.h"

const float Loop::MIN_VOL = 0.01;

// *********** CORE

Snapshot *Fweelin::getSNAP (int idx) {
  if (idx >= 0 && idx < cfg->GetMaxSnapshots())
    return &snaps[idx];
  else
    return 0;
}

void Snapshot::CreateSnapshot (char *name, LoopManager *lm, TriggerMap *tmap) {
  if (exists && this->name != 0 && name == 0) {
    // Preserve name of snapshot
    DeleteSnapshot(0);
  } else  
    DeleteSnapshot();

  exists = 1;
  if (this->name == 0 && name != 0) {
    this->name = new char[strlen(name)+1];
    strcpy(this->name,name);
  }

  if (lm != 0) {
    // Count all loops
    numls = tmap->CountLoops();
    if (numls > 0) {
      ls = new LoopSnapshot[numls];
      
      int idx = 0;
      for (int i = 0; i < tmap->GetMapSize(); i++) {
        if (tmap->GetMap(i) != 0) {
          Loop *l = tmap->GetMap(i);
          if (idx >= numls) {
            printf("CORE: ERROR: Loop count mismatch creating snapshot!\n");
            return;
          }
          
          ls[idx++] = LoopSnapshot(i,lm->GetStatus(i),
                                   l->vol,lm->GetTriggerVol(i));
        }
      }
    }
  }
};

// Trigger snapshot #idx - return nonzero on failure
char Fweelin::TriggerSnapshot (int idx) {
  Snapshot *s = getSNAP(idx);
  if (s != 0 && s->exists) {
    for (int i = 0; i < s->numls; i++) {
      LoopSnapshot *ls = &(s->ls[i]);

      loopmgr->SetLoopVolume(ls->l_idx,ls->l_vol);

      if (ls->status == T_LS_Off && loopmgr->IsActive(ls->l_idx)) {
        loopmgr->Deactivate(ls->l_idx);
      } else if (ls->status == T_LS_Playing || 
                 ls->status == T_LS_Overdubbing) {
        if (loopmgr->GetStatus(ls->l_idx) != T_LS_Playing) {
          // Loop not yet playing
          if (loopmgr->IsActive(ls->l_idx))
            loopmgr->Deactivate(ls->l_idx);
          loopmgr->Activate(ls->l_idx, 0, ls->t_vol);
        } else {
          // Loop already playing- adjust volume
          loopmgr->SetTriggerVol(ls->l_idx, ls->t_vol);
        }
      } 
    }

    return 0;
  } else
    return 1;
};

// Splits a saveable filename in the format 'basename-hash-objectname'
// into its base name, hash and object name components
//
// Returns zero on success
char Saveable::SplitFilename(char *filename, int baselen, char *basename, 
                             char *hash, char *objname,
                             int maxlen) {
  // Loop exists, use combination of time and hash as name
  char *slashptr = filename + baselen;

  if (slashptr < filename+strlen(filename)) {
    char *slashptr2 = strchr(slashptr+1,'-'),
      *extptr = strrchr(filename,'.');
    
    if (extptr == 0)
      extptr = filename+strlen(filename); // No extension
    
    // Extract base name
    int len = 0;
    if (basename != 0) {
      len = MIN(baselen,maxlen-1);
      memcpy(basename,filename,sizeof(char)*len);
      basename[len] = '\0';
    }

    // Extract hash
    char *breaker = (slashptr2 != 0 ? slashptr2 : extptr);
    if (strlen(slashptr+1) - strlen(breaker) == SAVEABLE_HASH_LENGTH*2) {
      if (hash != 0) {
        len = MIN(SAVEABLE_HASH_LENGTH*2,maxlen-1);
        memcpy(hash,slashptr+1,sizeof(char)*len);
        hash[len] = '\0';
      }
    } else {
      printf("SAVEABLE: Invalid hash within filename: '%s'\n",
             filename);
      return 1;
    }
    
    // Now check if the filename also contains an object name-
    // this would be placed after the hash
    if (objname != 0) {
      if (slashptr2 != 0) {
        // Name
        len = strlen(slashptr2+1) - strlen(extptr);
        len = MIN(len,maxlen-1);
        memcpy(objname,slashptr2+1,sizeof(char)*len);
        objname[len] = '\0';
      } else      
        strcpy(objname,"");
    }
  } else {
    printf("SAVEABLE: Invalid filename for extracting hash/name: '%s'\n",
           filename);
    return 1;
  }
  
  return 0;
};

void Saveable::RenameSaveable(char **filename_ptr, int baselen, 
                              char *newname, const char **exts, int num_exts) {
  // Parse filename to extract hash part
  char fn_base[FWEELIN_OUTNAME_LEN], 
    fn_hash[FWEELIN_OUTNAME_LEN],
    fn_name[FWEELIN_OUTNAME_LEN];
  if (Saveable::SplitFilename(*filename_ptr,baselen,fn_base,fn_hash,fn_name,
                              FWEELIN_OUTNAME_LEN))
    printf("SAVEABLE: Can't rename '%s'- poorly formatted filename.\n",
           *filename_ptr);
  else {
    char tmp[FWEELIN_OUTNAME_LEN];
    strncpy(tmp,*filename_ptr,FWEELIN_OUTNAME_LEN);
    tmp[FWEELIN_OUTNAME_LEN-1] = '\0';

    delete[] *filename_ptr;
    *filename_ptr = new char[strlen(fn_base)+1+
                             strlen(fn_hash)+1+
                             strlen(newname)+1];
    if (strlen(newname) > 0) 
      sprintf(*filename_ptr,"%s-%s-%s",
              fn_base,fn_hash,newname);
    else
      sprintf(*filename_ptr,"%s-%s",
              fn_base,fn_hash);

    char tmp_a[FWEELIN_OUTNAME_LEN],
      tmp_b[FWEELIN_OUTNAME_LEN];
    for (int i = 0; i < num_exts; i++) {
      // Add each type of extension provided and rename the file
      snprintf(tmp_a,FWEELIN_OUTNAME_LEN,"%s%s",tmp,exts[i]);
      snprintf(tmp_b,FWEELIN_OUTNAME_LEN,"%s%s",*filename_ptr,exts[i]);

      if (!rename(tmp_a,tmp_b))
        printf("SAVEABLE: Rename file '%s' -> '%s'\n",tmp_a,tmp_b);
      //else 
      //printf("SAVEABLE: File '%s' not found for rename\n",tmp_a);
    }
  }
};

// This is for renaming an item in memory, so that the disk corresponds
// with the new name
void Saveable::RenameSaveable(char *librarypath, char *basename, 
                              char *old_objname, char *nw_objname,
                              const char **exts, int num_exts,
                              char **old_filename, char **new_filename) {
  if (savestatus == SAVE_DONE) {
    // OK, we have to rename on disk

    // Get filename to rename
    GET_SAVEABLE_HASH_TEXT(GetSaveHash());

    *old_filename = new char[FWEELIN_OUTNAME_LEN];
    *new_filename = new char[FWEELIN_OUTNAME_LEN];

    for (int i = 0; i < num_exts; i++) {
      // Add each type of extension provided and rename the file

      if (old_objname == 0 || strlen(old_objname) == 0) 
        snprintf(*old_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s%s",
                 librarypath,basename,hashtext,exts[i]);
      else 
        snprintf(*old_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s%s",
                 librarypath,basename,hashtext,old_objname,exts[i]);

      if (nw_objname == 0 || strlen(nw_objname) == 0) 
        snprintf(*new_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s%s",
                 librarypath,basename,hashtext,exts[i]);
      else 
        snprintf(*new_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s%s",
                 librarypath,basename,hashtext,nw_objname,exts[i]);

      printf("SAVEABLE: Rename file '%s' -> '%s'\n",
             *old_filename,*new_filename);
      rename(*old_filename,*new_filename);
    }

    // Get names without extensions
    if (old_objname == 0) 
      snprintf(*old_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s",
               librarypath,basename,hashtext);
    else 
      snprintf(*old_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s",
               librarypath,basename,hashtext,old_objname);
    
    if (nw_objname == 0) 
      snprintf(*new_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s",
               librarypath,basename,hashtext);
    else 
      snprintf(*new_filename,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s",
               librarypath,basename,hashtext,nw_objname);
  }
};

// Save loop
void Loop::Save(Fweelin *app) {
  // Queue save
  app->getLOOPMGR()->AddLoopToSaveQueue(this);
};

void LoopManager::AddToSaveQueue(Event *ev) {
  numsave++;
  EventManager::QueueEvent(&savequeue,ev);
};

void LoopManager::AddLoopToSaveQueue(Loop *l) {
  if (!autosave && l->GetSaveStatus() == NO_SAVE) {
    numsave++;

    LoopListEvent *ll = (LoopListEvent *) 
      Event::GetEventByType(T_EV_LoopList,1);
    ll->l = l;
        
    EventManager::QueueEvent(&savequeue,ll);
  }
};

void LoopManager::AddLoopToLoadQueue(char *filename, int index, float vol) {
  numload++;

  LoopListEvent *ll = (LoopListEvent *) 
    Event::GetEventByType(T_EV_LoopList,1);
  strcpy(ll->l_filename,filename);
  ll->l_idx = index;
  ll->l_vol = vol;
  
  EventManager::QueueEvent(&loadqueue,ll);
};

// Adds the loop with given filename to the loop browser br
void LoopManager::AddLoopToBrowser(Browser *br, char *filename) {
  char tmp[FWEELIN_OUTNAME_LEN];
  
  struct stat st;
  if (stat(filename,&st) == 0) {
    char default_name = 
      br->GetDisplayName(filename,&st.st_mtime,tmp,FWEELIN_OUTNAME_LEN);

    br->AddItem(new LoopBrowserItem(st.st_mtime,tmp,default_name,filename),1);
  }
};

// Populate the loop browser with any loops on disk
void LoopManager::SetupLoopBrowser() {
  Browser *br = app->getBROWSER(B_Loop);

  if (br != 0) {
    // Clear
    br->ClearAllItems();

    // Look for loops on disk 
    glob_t globbuf;
    char tmp[FWEELIN_OUTNAME_LEN];
    for (codec lformat = FIRST_FORMAT; lformat < END_OF_FORMATS; 
         lformat = (codec) (lformat+1)) {
      snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s*%s",
             app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_LOOP_NAME,
             app->getCFG()->GetAudioFileExt(lformat)); 
      printf("BROWSER: (Loop) Scanning for loops in library: %s\n",tmp);
      if (glob(tmp, 0, NULL, &globbuf) == 0) {
        for (size_t i = 0; i < globbuf.gl_pathc; i++) {
          //printf("BROWSER: (Loop) Loop: %s\n",globbuf.gl_pathv[i]);
          AddLoopToBrowser(br,globbuf.gl_pathv[i]);
        }

        br->AddDivisions(FWEELIN_FILE_BROWSER_DIVISION_TIME);
        br->MoveToBeginning();
        globfree(&globbuf);
      }
    }
  }
};

// Adds the scene with given filename to the scene browser br
SceneBrowserItem *LoopManager::AddSceneToBrowser(Browser *br, char *filename) {
  char tmp[FWEELIN_OUTNAME_LEN];
  SceneBrowserItem *ret = 0;

  struct stat st;
  if (stat(filename,&st) == 0) {
    char default_name = 
      br->GetDisplayName(filename,&st.st_mtime,tmp,FWEELIN_OUTNAME_LEN);

    br->AddItem(ret = 
                new SceneBrowserItem(st.st_mtime,tmp,default_name,filename),1);
  }

  return ret;
};

// Populate the scene browser with any scenes on disk
void LoopManager::SetupSceneBrowser() {
  Browser *br = app->getBROWSER(B_Scene);

  if (br != 0) {
    // Clear
    br->ClearAllItems();

    // Look for scenes on disk 
    glob_t globbuf;
    char tmp[FWEELIN_OUTNAME_LEN];
    snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s*%s",
             app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_SCENE_NAME,
             FWEELIN_OUTPUT_DATA_EXT);
    printf("BROWSER: (Scene) Scanning for scenes in library: %s\n",tmp);
    if (glob(tmp, 0, NULL, &globbuf) == 0) {
      for (size_t i = 0; i < globbuf.gl_pathc; i++) {
        // printf("BROWSER: (Scene) Scene: %s\n",globbuf.gl_pathv[i]);
        AddSceneToBrowser(br,globbuf.gl_pathv[i]);
      }
      br->AddDivisions(FWEELIN_FILE_BROWSER_DIVISION_TIME);
      br->MoveToBeginning();
      globfree(&globbuf);
    }
  }
};

void LoopManager::ItemBrowsed(BrowserItem *i) {};
void LoopManager::ItemSelected(BrowserItem *i) {
  switch (i->GetType()) {
  case B_Loop: 
    printf("DISK: Load '%s'\n",((LoopBrowserItem *) i)->filename);
    LoadLoop(((LoopBrowserItem *) i)->filename,loadloopid,
             newloopvol / GetOutputVolume());
    break;
    
  case B_Scene:
    printf("DISK: Load '%s'\n",((SceneBrowserItem *) i)->filename);
    LoadScene((SceneBrowserItem *) i);
    break;

  default:
    break;
  }
};
void LoopManager::ItemRenamed(BrowserItem *i) {
  switch (i->GetType()) {
  case B_Loop_Tray:
    // Change name inside the loop
    {
      LoopTrayItem *curl = (LoopTrayItem *) i;
      char *old_filename = 0, 
        *new_filename = 0;
      
      // Rename on disk
      const static char *exts[] = {app->getCFG()->GetAudioFileExt(curl->l->format),
                                   FWEELIN_OUTPUT_DATA_EXT};
      curl->l->RenameSaveable(app->getCFG()->GetLibraryPath(), 
                              FWEELIN_OUTPUT_LOOP_NAME,
                              curl->l->name, curl->name,
                              exts, 2,
                              &old_filename,
                              &new_filename);
    
      // We also need to rename in the loop browser
      if (app->getBROWSER(B_Loop) != 0) 
        app->getBROWSER(B_Loop)->
          ItemRenamedOnDisk(old_filename,new_filename,curl->name);
      
      if (old_filename != 0)
        delete[] old_filename;
      if (new_filename != 0)
        delete[] new_filename;

      // And in memory..
      RenameLoop(curl->l,curl->name);
    }
    break;

  case B_Loop:
    {
      // Name change on disk
      int baselen = strlen(app->getCFG()->GetLibraryPath()) + 1 +
        strlen(FWEELIN_OUTPUT_LOOP_NAME);

      // Add all audio format names + XML to extension list
      int numexts = END_OF_FORMATS + 1;
      char *exts[numexts];
      for (codec c = FIRST_FORMAT; c < END_OF_FORMATS; c = (codec) (c+1))
        exts[c] = app->getCFG()->GetAudioFileExt(c);
      exts[END_OF_FORMATS] = FWEELIN_OUTPUT_DATA_EXT;

      // Rename all possible audio files + XML metadata to new name
      printf("DISK: Rename '%s'\n",((LoopBrowserItem *) i)->filename);
      Saveable::RenameSaveable(&((LoopBrowserItem *) i)->filename,baselen,
                               i->name,(const char **) exts,numexts);

      // Is this loop loaded? If so, rename it

      // Find loop in memory (by hash, extracted from filename)
      char fn_hash[FWEELIN_OUTNAME_LEN];
      if (!Saveable::SplitFilename(((LoopBrowserItem *) i)->filename,
                                   baselen,0,fn_hash,0,FWEELIN_OUTNAME_LEN)) {
        // Convert text 'fn_hash' to binary hash and scan for it
        Saveable tmp;
        if (!(tmp.SetSaveableHashFromText(fn_hash))) {
          int foundidx;
          if ((foundidx = 
               app->getTMAP()->ScanForHash(tmp.GetSaveHash())) != -1) {
            // This loop -is- loaded, rename in map and in loop tray
            // printf("loop renamed is also in memory: %d\n",foundidx);
            Loop *foundloop = GetSlot(foundidx);
            
            // Rename in memory
            RenameLoop(foundloop,i->name);
            
            // We have to notify the LoopTray of the new name given
            LoopTray *tray = (LoopTray *) app->getBROWSER(B_Loop_Tray);
            if (tray != 0)
              tray->ItemRenamedFromOutside(foundloop,i->name);
          }     
        }
      }      
    }
    break;
    
  case B_Scene:
    {
      int baselen = strlen(app->getCFG()->GetLibraryPath()) + 1 +
        strlen(FWEELIN_OUTPUT_SCENE_NAME);
      const static char *exts[] = {FWEELIN_OUTPUT_DATA_EXT};
      
      printf("DISK: Rename '%s'\n",((SceneBrowserItem *) i)->filename);
      Saveable::RenameSaveable(&((SceneBrowserItem *) i)->filename,baselen,
                               i->name,exts,1);
    }
    break;

  default:
    break;
  }
};

LoopManager::LoopManager (Fweelin *app) : 
  renamer(0), rename_loop(0), 
  savequeue(0), loadqueue(0), cursave(0), curload(0), numsave(0), numload(0),
  loadloopid(0), needs_saving_stamp(0),
  default_looprange(Range(0,app->getCFG()->GetNumTriggers())),

  autosave(0), app(app), newloopvol(1.0), subdivide(1), curpulseindex(-1) {
  pthread_mutex_init (&loops_lock,0);

  int mapsz = app->getTMAP()->GetMapSize();

  plist = new Processor *[mapsz];
  status = new LoopStatus[mapsz];
  waitactivate = new int[mapsz];
  waitactivate_shot = new char[mapsz];
  waitactivate_vol = new float[mapsz];
  waitactivate_od = new char[mapsz];
  waitactivate_od_fb = new float *[mapsz];

  numloops = 0;
  numrecordingloops = 0;
  
  lastrecidx = new int[LAST_REC_COUNT];
  memset(lastrecidx, 0, sizeof(int) * LAST_REC_COUNT);
  
  memset(plist, 0, sizeof(Processor *) * mapsz);
  int lst = T_LS_Off;
  memset(status, lst, sizeof(LoopStatus) * mapsz);
  memset(waitactivate, 0, sizeof(int) * mapsz);
  memset(waitactivate_shot, 0, sizeof(char) * mapsz);
  memset(waitactivate_vol, 0, sizeof(float) * mapsz);
  memset(waitactivate_od, 0, sizeof(char) * mapsz);
  memset(waitactivate_od_fb, 0, sizeof(float) * mapsz);
  memset(pulses, 0, sizeof(Pulse *) * MAX_PULSES);

  // Turn on block read/write managers for loading & saving loops
  bread = ::new BlockReadManager(0,this,app->getBMG(),
                                 app->getCFG()->loop_peaksavgs_chunksize);
  bwrite = ::new BlockWriteManager(0,this,app->getBMG());
  app->getBMG()->AddManager(bread);
  app->getBMG()->AddManager(bwrite);

  // Listen for important events
  app->getEMG()->ListenEvent(this,0,T_EV_EndRecord);
  app->getEMG()->ListenEvent(this,0,T_EV_ToggleDiskOutput);
  app->getEMG()->ListenEvent(this,0,T_EV_ToggleSelectLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_SelectOnlyPlayingLoops);
  app->getEMG()->ListenEvent(this,0,T_EV_SelectAllLoops);
  app->getEMG()->ListenEvent(this,0,T_EV_InvertSelection);
  app->getEMG()->ListenEvent(this,0,T_EV_CreateSnapshot);
  app->getEMG()->ListenEvent(this,0,T_EV_RenameSnapshot);
  app->getEMG()->ListenEvent(this,0,T_EV_TriggerSnapshot);
  app->getEMG()->ListenEvent(this,0,T_EV_SetAutoLoopSaving);
  app->getEMG()->ListenEvent(this,0,T_EV_SaveLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_SaveNewScene);
  app->getEMG()->ListenEvent(this,0,T_EV_SaveCurrentScene);
  app->getEMG()->ListenEvent(this,0,T_EV_SetLoadLoopId);
  app->getEMG()->ListenEvent(this,0,T_EV_SetDefaultLoopPlacement);

  app->getEMG()->ListenEvent(this,0,T_EV_SlideMasterInVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SlideMasterOutVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SlideInVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SetMasterInVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SetMasterOutVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SetInVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_ToggleInputRecord);

  app->getEMG()->ListenEvent(this,0,T_EV_DeletePulse);
  app->getEMG()->ListenEvent(this,0,T_EV_SelectPulse);
  app->getEMG()->ListenEvent(this,0,T_EV_TapPulse);
  app->getEMG()->ListenEvent(this,0,T_EV_SwitchMetronome);
  app->getEMG()->ListenEvent(this,0,T_EV_SetSyncType);
  app->getEMG()->ListenEvent(this,0,T_EV_SetSyncSpeed);
  app->getEMG()->ListenEvent(this,0,T_EV_SetMidiSync);

  app->getEMG()->ListenEvent(this,0,T_EV_SetTriggerVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_SlideLoopAmp);
  app->getEMG()->ListenEvent(this,0,T_EV_SetLoopAmp);
  app->getEMG()->ListenEvent(this,0,T_EV_AdjustLoopAmp);
  app->getEMG()->ListenEvent(this,0,T_EV_TriggerLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_TriggerSelectedLoops);
  app->getEMG()->ListenEvent(this,0,T_EV_SetSelectedLoopsTriggerVolume);
  app->getEMG()->ListenEvent(this,0,T_EV_AdjustSelectedLoopsAmp);

  app->getEMG()->ListenEvent(this,0,T_EV_MoveLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_RenameLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_EraseLoop);
  app->getEMG()->ListenEvent(this,0,T_EV_EraseAllLoops);
  app->getEMG()->ListenEvent(this,0,T_EV_EraseSelectedLoops);
  app->getEMG()->ListenEvent(this,0,T_EV_SlideLoopAmpStopAll);
};

LoopManager::~LoopManager() { 
  // Stop block read/write managers
  bread->End(0);
  bwrite->End();
  app->getBMG()->DelManager(bread);
  app->getBMG()->DelManager(bwrite);

  // Stop listening
  app->getEMG()->UnlistenEvent(this,0,T_EV_EndRecord);
  app->getEMG()->UnlistenEvent(this,0,T_EV_ToggleDiskOutput);
  app->getEMG()->UnlistenEvent(this,0,T_EV_ToggleSelectLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SelectOnlyPlayingLoops);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SelectAllLoops);
  app->getEMG()->UnlistenEvent(this,0,T_EV_InvertSelection);
  app->getEMG()->UnlistenEvent(this,0,T_EV_CreateSnapshot);
  app->getEMG()->UnlistenEvent(this,0,T_EV_RenameSnapshot);
  app->getEMG()->UnlistenEvent(this,0,T_EV_TriggerSnapshot);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetAutoLoopSaving);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SaveLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SaveNewScene);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SaveCurrentScene);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetLoadLoopId);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetDefaultLoopPlacement);

  app->getEMG()->UnlistenEvent(this,0,T_EV_SlideMasterInVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SlideMasterOutVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SlideInVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetMasterInVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetMasterOutVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetInVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_ToggleInputRecord);

  app->getEMG()->UnlistenEvent(this,0,T_EV_DeletePulse);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SelectPulse);
  app->getEMG()->UnlistenEvent(this,0,T_EV_TapPulse);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SwitchMetronome);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetSyncType);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetSyncSpeed);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetMidiSync);

  app->getEMG()->UnlistenEvent(this,0,T_EV_SetTriggerVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SlideLoopAmp);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetLoopAmp);
  app->getEMG()->UnlistenEvent(this,0,T_EV_AdjustLoopAmp);
  app->getEMG()->UnlistenEvent(this,0,T_EV_TriggerLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_TriggerSelectedLoops);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SetSelectedLoopsTriggerVolume);
  app->getEMG()->UnlistenEvent(this,0,T_EV_AdjustSelectedLoopsAmp);

  app->getEMG()->UnlistenEvent(this,0,T_EV_MoveLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_RenameLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_EraseLoop);
  app->getEMG()->UnlistenEvent(this,0,T_EV_EraseAllLoops);
  app->getEMG()->UnlistenEvent(this,0,T_EV_EraseSelectedLoops);
  app->getEMG()->UnlistenEvent(this,0,T_EV_SlideLoopAmpStopAll);

  EventManager::DeleteQueue(savequeue);
  EventManager::DeleteQueue(loadqueue);

  // Let BMG know that we are ending
  app->getBMG()->RefDeleted((AutoWriteControl *) this);

  delete[] lastrecidx;

  delete[] plist; delete[] status; 
  delete[] waitactivate; delete[] waitactivate_shot; 
  delete[] waitactivate_vol; delete[] waitactivate_od;
  delete[] waitactivate_od_fb;

  pthread_mutex_destroy (&loops_lock);
};

// Get length returns the length of any loop on the specified index
nframes_t LoopManager::GetLength(int index) {
  if (status[index] == T_LS_Recording) {
    // Ooh, we are recording on this index. Get the current length
    return ((RecordProcessor *) plist[index])->GetRecordedLength();
  }
  else {
    Loop *cur = app->getTMAP()->GetMap(index);
    if (cur != 0)
      return cur->blocks->GetTotalLen();
  }

  return 0;
}

// Get length returns the length of any loop on the specified index
// Rounded to its currently quantized length
// Or 0 if the loop has no pulse
nframes_t LoopManager::GetRoundedLength(int index) {
  if (status[index] == T_LS_Recording) {
    // Return 0 when recording
    return 0;

    // Ooh, we are recording on this index. Get the current length
    // return ((RecordProcessor *) plist[index])->GetRecordedLength();
  }
  else {
    Loop *cur = app->getTMAP()->GetMap(index);
    if (cur != 0)
      if (cur->pulse != 0)
        return cur->pulse->QuantizeLength(cur->blocks->GetTotalLen());
      else
        return 0; // cur->blocks->GetTotalLen();
  }
  
  return 0;
}

float LoopManager::GetPos(int index) {
  if (status[index] == T_LS_Recording)
    return 0.0;
  else {
    Loop *cur = app->getTMAP()->GetMap(index);
    if (cur != 0 && plist[index] != 0) {
      nframes_t playedlen = 0;
      if (status[index] == T_LS_Playing)
        playedlen = ((PlayProcessor *) plist[index])->GetPlayedLength();
      else if (status[index] == T_LS_Overdubbing)
        playedlen = ((RecordProcessor *) plist[index])->GetRecordedLength();

      if (cur->pulse == 0) 
        return (float) playedlen / cur->blocks->GetTotalLen();
      else {
        if (cur->pulse->QuantizeLength(cur->blocks->GetTotalLen()) == 0) {
          printf("LoopManager: ERROR: Problem with quantize GetPos\n");
          exit(1);
        }
        return (float) playedlen / 
          cur->pulse->QuantizeLength(cur->blocks->GetTotalLen());
      }
    }
  }
  
  return 0.0;
}

// Get current # of samples into block chain with given index
nframes_t LoopManager::GetCurCnt(int index) {
  if (status[index] == T_LS_Recording)
    return 0;
  else {
    Loop *cur = app->getTMAP()->GetMap(index);
    if (cur != 0 && plist[index] != 0) {
      if (status[index] == T_LS_Playing)
        return ((PlayProcessor *) plist[index])->GetPlayedLength();
      else if (status[index] == T_LS_Overdubbing) 
        return ((RecordProcessor *) plist[index])->GetRecordedLength();
    }
  }
  
  return 0;
}

// Sets triggered volume on specified index
// If index is not playing, activates the index
void LoopManager::SetTriggerVol(int index, float vol) {
  if (status[index] == T_LS_Playing) 
    ((PlayProcessor *) plist[index])->SetPlayVol(vol);
  else if (status[index] == T_LS_Overdubbing) 
    ((RecordProcessor *) plist[index])->SetODPlayVol(vol);
}

// Gets trigger volume on specified index
// If index is not playing, returns 0
float LoopManager::GetTriggerVol(int index) {
  if (status[index] == T_LS_Playing)
    return ((PlayProcessor *) plist[index])->GetPlayVol();
  else if (status[index] == T_LS_Overdubbing) 
    return ((RecordProcessor *) plist[index])->GetODPlayVol();
  else
    return 0.0;
}

// Returns a loop with the specified index, if one exists
Loop *LoopManager::GetSlot(int index) {
  return app->getTMAP()->GetMap(index);
}

void LoopManager::AdjustOutputVolume(float adjust) {
  app->getRP()->AdjustOutputVolume(adjust);
}

void LoopManager::SetOutputVolume(float set, float logset) {
  if (set >= 0.)
    app->getRP()->SetOutputVolume(set);
  else if (logset >= 0.)
    app->getRP()->SetOutputVolume(DB2LIN(AudioLevel::fader_to_dB(logset, app->getCFG()->GetFaderMaxDB())));
}

float LoopManager::GetOutputVolume() {
  return app->getRP()->GetOutputVolume();
}

void LoopManager::AdjustInputVolume(float adjust) {
  app->getRP()->AdjustInputVolume(adjust);
}

void LoopManager::SetInputVolume(float set, float logset) {
  if (set >= 0.)
    app->getRP()->SetInputVolume(set);
  else if (logset >= 0.)
    app->getRP()->SetInputVolume(DB2LIN(AudioLevel::fader_to_dB(logset, app->getCFG()->GetFaderMaxDB())));
}

float LoopManager::GetInputVolume() {
  return app->getRP()->GetInputVolume();
}

void LoopManager::SetLoopVolume(int index, float val) {
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0) {
    // First, preprocess for smoothing
    Processor *p = GetProcessor(index);
    if (p != 0) 
      p->dopreprocess();

    if (val >= 0.0)
      lp->vol = val;
    else
      lp->vol = 0.0;
  }
}

float LoopManager::GetLoopVolume(int index) {
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0)
    return lp->vol;
  else
    return 1.0;
}

void LoopManager::AdjustLoopVolume(int index, float adjust) {
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0) {
    lp->dvol += adjust*app->getAUDIO()->GetTimeScale();
    if (lp->dvol < 0.0)
      lp->dvol = 0.0;
  }
}

void LoopManager::SetLoopdVolume(int index, float val) {
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0)
    lp->dvol = val;
}

float LoopManager::GetLoopdVolume(int index) {
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0)
    return lp->dvol;
  else
    return 1.0;
}

void LoopManager::SelectPulse (int pulseindex) {
  if (pulseindex == -1) {
    if (GetCurPulse() != 0) 
      GetCurPulse()->SetMIDIClock(0); // Stop MIDI clock
    
    //printf("**Select: No pulse\n");
    curpulseindex = -1;    
  } else if (pulseindex < 0 || pulseindex >= MAX_PULSES) {
    printf("CORE: Invalid pulse #%d, ignoring.\n",pulseindex);
    return;
  } else if (pulses[pulseindex] == 0) {
    //printf("New pulse[%d]: %d SUB: %d\n", pulseindex, lastindex, subdivide);
    CreatePulse(lastindex, pulseindex, subdivide);
  } else {
    //printf("Select pulse[%d]\n", pulseindex);
    curpulseindex = pulseindex;
    StripePulseOn(pulses[pulseindex]);
    
    // Select pulse, send MIDI start
    GetCurPulse()->SetMIDIClock(1);
  }
}

// Save a whole scene, with an optional filename-
// if none is given, saves a new scene
void TriggerMap::Save(Fweelin *app, char *filename) {
  if (GetSaveStatus() == NO_SAVE) {
    // Scene hash is generated from hash of all loops in the triggermap--
    // so start by saving all loops
    app->getLOOPMGR()->SetAutoLoopSaving(0);
    for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) 
      app->getLOOPMGR()->SaveLoop(i);

    // Now, we have to wait until all that saving is done.
    // Queue a scene marker event in the save queue
    SceneMarkerEvent *sEvt = (SceneMarkerEvent *) Event::GetEventByType(T_EV_SceneMarker,1);
    if (filename != 0)
      strncpy(sEvt->s_filename,filename,FWEELIN_OUTNAME_LEN);
    
    app->getLOOPMGR()->AddToSaveQueue(sEvt);
  }
};

void TriggerMap::SetMap (int index, Loop *smp) {
  if (index < 0 || index >= mapsize) {
    printf("SetMap: Invalid loop index!\n");
  }
  else {
    map[index] = smp;
    TouchMap();
    
    // Fire off a TriggerSet event
    TriggerSetEvent *tevt = (TriggerSetEvent *) 
      Event::GetEventByType(T_EV_TriggerSet);
    tevt->idx = index;
    tevt->nw = smp;
    app->getEMG()->BroadcastEventNow(tevt, this);
  }
};

void TriggerMap::GoSave(char *filename) {
  // All loops in the scene are now hashed and saved

  char newScene = (filename[0] == '\0');  // New scene or overwrite existing?
  if (newScene) {
    // Begin our save by generating a scene hash from the loop hashes
    // This will give us an appropriate scene filename
    MD5_CTX md5gen;
    MD5_Init(&md5gen);
    for (int i = 0; i < mapsize; i++)
      if (map[i] != 0) {
        if (map[i]->GetSaveStatus() == SAVE_DONE)
          // Update scene hash with hash from this loop
          MD5_Update(&md5gen,map[i]->GetSaveHash(),SAVEABLE_HASH_LENGTH);
        else
          printf("DISK: WARNING: Loop %d not saved yet but scene about to be "
                 "saved!\n",i);
      }
    
    // Done- compute our final hash
    MD5_Final(GetSaveHash(),&md5gen);
  }
  
  SetSaveStatus(SAVE_DONE);
    
  // Compose filenames & start writing
  char tmp[FWEELIN_OUTNAME_LEN];
  if (newScene) {
    GET_SAVEABLE_HASH_TEXT(GetSaveHash());
    snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s-%s%s",
             app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_SCENE_NAME,
             hashtext,FWEELIN_OUTPUT_DATA_EXT);
  } else
    snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s%s",
             filename,FWEELIN_OUTPUT_DATA_EXT);
             
  if (!newScene) {
    // Back up existing scene data
    struct stat st;
    if (stat(tmp,&st) == 0) {
      // First available backup filename
      char tmp2[FWEELIN_OUTNAME_LEN];
      int bCnt = 1;
      char go = 1;
      
      while (go) {
        snprintf(tmp2,FWEELIN_OUTNAME_LEN,"%s.backup.%d",tmp,bCnt);
        if (stat(tmp2,&st) != 0)
          go = 0; // Free backup filename
        else
          bCnt++;
      }
      
      char buf[FWEELIN_OUTNAME_LEN * 2 + 20];
      printf("INIT: Backup existing scene.\n");
      sprintf(buf,"mv \"%s\" \"%s\"",tmp,tmp2);
      printf("INIT: Executing: %s\n",buf);
      system(buf);      
    }
  }
  
  struct stat st;
  printf("DISK: Opening %s '%s' for saving.\n",
         (newScene ? "new scene" : "existing scene"),
         tmp);
  if (newScene && stat(tmp,&st) == 0) {
    printf("DISK: ERROR: MD5 collision while saving scene- file exists!\n");
  } else {
    // Save scene XML data
    xmlDocPtr ldat = xmlNewDoc((xmlChar *) "1.0");
    if (ldat != 0) {
      const static int XT_LEN = 10;
      char xmltmp[XT_LEN];
      
      // Scene
      ldat->children = xmlNewDocNode(ldat,0,
                                     (xmlChar *) FWEELIN_OUTPUT_SCENE_NAME,0);

      // Loops
      for (int i = 0; i < mapsize; i++)
        if (map[i] != 0 && map[i]->GetSaveStatus() == SAVE_DONE) {
          xmlNodePtr lp = xmlNewChild(ldat->children, 0, 
                                      (xmlChar *) FWEELIN_OUTPUT_LOOP_NAME, 0);

          // Loop index
          snprintf(xmltmp,XT_LEN,"%d",i);
          xmlSetProp(lp,(xmlChar *) "loopid",(xmlChar *) xmltmp);

          // Loop hash (used to find the loop on disk)
          unsigned char *sh = map[i]->GetSaveHash();
          GET_SAVEABLE_HASH_TEXT(sh);
          xmlSetProp(lp,(xmlChar *) "hash",(xmlChar *) hashtext);

          // Loop volume
          snprintf(xmltmp,XT_LEN,"%.5f",map[i]->vol);
          xmlSetProp(lp,(xmlChar *) "volume",(xmlChar *) xmltmp);
        }

      // Snapshots
      Snapshot *snaps = app->getSNAPS();
      for (int i = 0; i < app->getCFG()->GetMaxSnapshots(); i++) {
        if (snaps[i].exists) {
          Snapshot *s = &snaps[i];
          xmlNodePtr sp = xmlNewChild(ldat->children, 0, 
                                      (xmlChar *) FWEELIN_OUTPUT_SNAPSHOT_NAME, 0);

          // Snapshot index
          snprintf(xmltmp,XT_LEN,"%d",i);
          xmlSetProp(sp,(xmlChar *) "snapid",(xmlChar *) xmltmp);

          // Name
          if (s->name != 0)
            xmlSetProp(sp,(xmlChar *) "name",(xmlChar *) s->name);

          for (int j = 0; j < s->numls; j++) {
            LoopSnapshot *ls = &(s->ls[j]);
            xmlNodePtr slp = xmlNewChild(sp, 0, 
                                         (xmlChar *) FWEELIN_OUTPUT_LOOPSNAPSHOT_NAME, 0);
            
            // Loop index
            snprintf(xmltmp,XT_LEN,"%d",ls->l_idx);
            xmlSetProp(slp,(xmlChar *) "loopid",(xmlChar *) xmltmp);

            // Loop status
            snprintf(xmltmp,XT_LEN,"%d",ls->status);
            xmlSetProp(slp,(xmlChar *) "status",(xmlChar *) xmltmp);

            // Loop volume
            snprintf(xmltmp,XT_LEN,"%.5f",ls->l_vol);
            xmlSetProp(slp,(xmlChar *) "loopvol",(xmlChar *) xmltmp);

            // Trigger volume
            snprintf(xmltmp,XT_LEN,"%.5f",ls->t_vol);
            xmlSetProp(slp,(xmlChar *) "triggervol",(xmlChar *) xmltmp);
          }
        }
      }

      xmlSaveFormatFile(tmp,ldat,1);
      xmlFreeDoc(ldat);

      if (newScene) {
        // Add scene to browser so we can load it
        Browser *br = app->getBROWSER(B_Scene);
        if (br != 0) {
          app->setCURSCENE(app->getLOOPMGR()->AddSceneToBrowser(br,tmp));
          br->AddDivisions(FWEELIN_FILE_BROWSER_DIVISION_TIME);
        }
      }

      printf("DISK: Close output.\n");
    }
  }
};

// If we are autosaving, we have to maintain a list of new loops to be saved
void LoopManager::CheckSaveMap() {
  if (needs_saving_stamp != app->getTMAP()->GetLastUpdate()) {
    //printf("Rebuild save map.\n");

    // No, rebuild!
    numsave = 0;
    savequeue = EventManager::DeleteQueue(savequeue);

    // Scan for loops that haven't yet been saved, add them to our list
    TriggerMap *tmap = app->getTMAP();
    int mapsz = tmap->GetMapSize();
    for (int i = 0; i < mapsz; i++) {
      Loop *l = tmap->GetMap(i);
      if (l != 0 && l->GetSaveStatus() == NO_SAVE) {
        // Loop exists but not saved-- add to our map
        LoopListEvent *ll = (LoopListEvent *) 
          Event::GetEventByType(T_EV_LoopList,1);
        ll->l = l;
        
        numsave++;
        EventManager::QueueEvent(&savequeue,ll);
      }
    }

    // Now we've updated map
    needs_saving_stamp = tmap->GetLastUpdate();
  } else {
    //printf("Stamp match: %lf\n",needs_saving_stamp);
  }
}

// Saves loop XML data & prepares to save loop audio
void LoopManager::SetupSaveLoop(Loop *l, int l_idx, FILE **out, 
                                AudioBlock **b, 
                                AudioBlockIterator **i,
                                nframes_t *len) {
  const static nframes_t LOOP_HASH_CHUNKSIZE = 10000;

  if (l->GetSaveStatus() == NO_SAVE) {
    // Now return blocks from this loop to save
    *b = l->blocks;

#if 0
    if (l->pulse != 0)
      // Loop is syncronized to a pulse- quantize length
      *len = l->pulse->QuantizeLength(l->blocks->GetTotalLen());
    else
#endif

      // Take length from blocks
      *len = l->blocks->GetTotalLen();
    *i = 0;
    
    // Generate hash from audio data
    double hashtime = mygettime();

    // *** Hopefully this won't take so long- or we may have to split it up
    // as we split up the write phase
    AudioBlockIterator *hashi = new AudioBlockIterator(l->blocks,
                                                       LOOP_HASH_CHUNKSIZE);
    MD5_CTX md5gen;
    MD5_Init(&md5gen);
    char go = 1;
    char stereo = l->blocks->IsStereo();
    
    do {
      nframes_t pos = hashi->GetTotalLength2Cur(),
        remaining = *len-pos;
      nframes_t num = MIN(LOOP_HASH_CHUNKSIZE,remaining);
      
      sample_t *ibuf[2];
      if (stereo) {
        // Stereo
        hashi->GetFragment(&ibuf[0],&ibuf[1]);
        MD5_Update(&md5gen,ibuf[0],sizeof(sample_t) * num);
        MD5_Update(&md5gen,ibuf[1],sizeof(sample_t) * num);
      } else {
        // Mono
        hashi->GetFragment(&ibuf[0],0);
        MD5_Update(&md5gen,ibuf[0],sizeof(sample_t) * num);
      }
      
      if (remaining <= LOOP_HASH_CHUNKSIZE) {
        // Finished encoding
        go = 0;
      } else
        hashi->NextFragment();
    } while (go);
    
    // Done- compute final hash
    MD5_Final(l->GetSaveHash(),&md5gen);
    l->SetSaveStatus(SAVE_DONE);
    delete hashi;

    double dhashtime = mygettime()-hashtime;
    printf("HASH TIME: %f ms\n",dhashtime * 1000);

    // Compose filenames & start writing
    char tmp[FWEELIN_OUTNAME_LEN];
    GET_SAVEABLE_HASH_TEXT(l->GetSaveHash());
    if (l->name == 0 || strlen(l->name) == 0)
      snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s-%s%s",
               app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_LOOP_NAME,
               hashtext,
               app->getCFG()->GetAudioFileExt(app->getCFG()->GetLoopOutFormat()));
    else
      snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s%s",
               app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_LOOP_NAME,
               hashtext,l->name,
               app->getCFG()->GetAudioFileExt(app->getCFG()->GetLoopOutFormat()));

    struct stat st;
    printf("DISK: Opening '%s' for saving.\n",tmp);
    if (stat(tmp,&st) == 0) {
      printf("DISK: ERROR: MD5 collision while saving loop- file exists!\n");

      *b = 0;
      *len = 0;
      *i = 0;
      if (*out != 0) {
        fclose(*out);
        *out = 0;
      }
    } else {
      // Go save!
      *out = fopen(tmp,"wb");
      if (*out == 0) {
        printf("DISK: ERROR: Couldn't open file! Does the folder exist and "
               "do you have write permission?\n");
        *b = 0;
        *len = 0;
        *i = 0;
        if (*out != 0) {
          fclose(*out);
          *out = 0;
        }       
      } else {
        // Add loop to browser so we can load it
        Browser *br = app->getBROWSER(B_Loop);
        if (br != 0) {
          AddLoopToBrowser(br,tmp);
          br->AddDivisions(FWEELIN_FILE_BROWSER_DIVISION_TIME);
        }

        // Main file open, now save loop XML data
        if (l->name == 0 || strlen(l->name) == 0)
          snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s-%s%s",
                   app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_LOOP_NAME,
                   hashtext,FWEELIN_OUTPUT_DATA_EXT);
        else
          snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s-%s-%s%s",
                   app->getCFG()->GetLibraryPath(),FWEELIN_OUTPUT_LOOP_NAME,
                   hashtext,l->name,FWEELIN_OUTPUT_DATA_EXT);

        xmlDocPtr ldat = xmlNewDoc((xmlChar *) "1.0");
        if (ldat != 0) {
          const static int XT_LEN = 10;
          char xmltmp[XT_LEN];

          ldat->children = xmlNewDocNode(ldat,0,
            (xmlChar *) FWEELIN_OUTPUT_LOOP_NAME,0);

          // version
          snprintf(xmltmp,XT_LEN,"%d",LOOP_SAVE_FORMAT_VERSION);
          xmlSetProp(ldat->children,(xmlChar *) "version",(xmlChar *) xmltmp);

          // # beats
          snprintf(xmltmp,XT_LEN,"%ld",l->nbeats);
          xmlSetProp(ldat->children,(xmlChar *) "nbeats",(xmlChar *) xmltmp);

          // pulse length
          if (l->pulse == 0)
            xmlSetProp(ldat->children,(xmlChar *) "pulselen",(xmlChar *) "0");
          else {
            snprintf(xmltmp,XT_LEN,"%d",l->pulse->GetLength());
            xmlSetProp(ldat->children,(xmlChar *) "pulselen",
                       (xmlChar *) xmltmp);
          }
          xmlSaveFormatFile(tmp,ldat,1);
          xmlFreeDoc(ldat);
        }
      }
    }
  } else {
    printf("DISK: WARNING: Loop marked already saved.\n");

    *b = 0;
    *len = 0;
    *i = 0;
    if (*out != 0) {
      fclose(*out);
      *out = 0;
    }
  }
};

// Loads loop XML data & prepares to load loop audio
int LoopManager::SetupLoadLoop(FILE **in, char *smooth_end, Loop **new_loop, 
                               int l_idx, float l_vol, char *l_filename) {
  // Open up right file and begin loading
  char tmp[FWEELIN_OUTNAME_LEN];
  codec format = UNKNOWN;
  // Try exact filename with all format types
  for (codec i = FIRST_FORMAT; i < END_OF_FORMATS; i = (codec) (i+1))
  {
    snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s%s",l_filename,
             app->getCFG()->GetAudioFileExt(i));
    *in = fopen(tmp,"rb");
    if (*in != 0) {
      printf("DISK: Open loop '%s'\n",tmp);
      bread->SetLoopType(i);
      format = i;
      break;
    }
  } 

  if (*in == 0) {
    // No go, try wildcard search with all format types
    for (codec i = FIRST_FORMAT; i < END_OF_FORMATS; i = (codec) (i+1)) {
      snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s*%s",l_filename,
               app->getCFG()->GetAudioFileExt(i));
      glob_t globbuf;
      if (glob(tmp, 0, NULL, &globbuf) == 0) {
        for (size_t j = 0; *in == 0 && j < globbuf.gl_pathc; j++) {
          printf("DISK: Open loop '%s'\n",globbuf.gl_pathv[j]);
          *in = fopen(globbuf.gl_pathv[j],"rb");
        }
        globfree(&globbuf);
      }
      if (*in != 0) {
        bread->SetLoopType(i);
        format = i;
        break;
      } 
    }
    if (*in == 0) {
      printf("DISK: ERROR: Couldn't open loop '%s'!\n",tmp);
      return 1;
    }
  }

  // Main file open, now load loop XML data
  snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s%s",
           l_filename,FWEELIN_OUTPUT_DATA_EXT);
  
  // Create loop data
  *new_loop = new Loop(0,0,1.0,l_vol,0,format);

  struct stat st;
  int result = 1;
  if (stat(tmp,&st) != 0) {
    // Try loading with wildcard
    snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s*%s",
             l_filename,FWEELIN_OUTPUT_DATA_EXT);
    glob_t globbuf;

    if (glob(tmp, 0, NULL, &globbuf) == 0) {
      for (size_t i = 0; result != 0 && i < globbuf.gl_pathc; i++) {
        result = stat(globbuf.gl_pathv[i],&st);
        if (result == 0)
          strncpy(tmp,globbuf.gl_pathv[i],
                  FWEELIN_OUTNAME_LEN); // Save the name for later
      }
      globfree(&globbuf);
    }

    if (result != 0)
      printf("DISK: WARNING: Loop data '%s' missing!\n"
             "I will load just the raw audio.\n",tmp);
  } else
    result = 0;

  xmlDocPtr ldat = 0;
  if (result == 0)
    ldat = xmlParseFile(tmp);
  if (ldat == 0)
    printf("DISK: WARNING: Loop data '%s' invalid!\n"
           "I will load just the raw audio.\n",tmp);
  else {
    xmlNode *root = xmlDocGetRootElement(ldat);
    
    // Extract hash from filename
    char fn_hash[FWEELIN_OUTNAME_LEN],
      loopname[FWEELIN_OUTNAME_LEN];
    int baselen = strlen(app->getCFG()->GetLibraryPath()) + 1 +
      strlen(FWEELIN_OUTPUT_LOOP_NAME);
    if (!Saveable::SplitFilename(tmp,baselen,0,fn_hash,loopname,
                                 FWEELIN_OUTNAME_LEN)) {
      // Set hash from filename
      (*new_loop)->SetSaveableHashFromText(fn_hash);
      
      // GET_SAVEABLE_HASH_TEXT((*new_loop)->GetSaveHash());
      // printf("md5: %s\n",hashtext);
      
      // First, check if this loop has already been loaded
      // by scanning for another loop with the same hash
      int dupidx;
      if ((dupidx = 
           app->getTMAP()->ScanForHash((*new_loop)->GetSaveHash())) != -1) {
        printf("DISK: (DUPLICATE) Loop to load is already loaded at "
               "ID #%d.\n",dupidx);
        
        delete (*new_loop);
        *new_loop = 0;
        fclose(*in);
        *in = 0;
        
        return 1;
      }
      
      // Set loop name from filename
      (*new_loop)->name = new char[strlen(loopname)+1];
      strcpy((*new_loop)->name,loopname);
    } else
      printf("DISK: Loop filename '%s' missing hash!\n",l_filename);
    
    // version
    xmlChar *n = xmlGetProp(root, (const xmlChar *) "version");
    if (n != 0) {
      if (atoi((char *) n) >= 1)
        // New format of loop save, so smooth end
        *smooth_end = 1;
      else
        *smooth_end = 0;
      
      xmlFree(n);
    } else {
      *smooth_end = 0;
      printf("DISK: Old format loop '%s'- loading with length fix.\n",
             l_filename);
    }
    
    // # beats
    n = xmlGetProp(root, (const xmlChar *) "nbeats");
    if (n != 0) {
      (*new_loop)->nbeats = atoi((char *) n);
      xmlFree(n);
    }
    
    // pulse length
    if ((n = xmlGetProp(root, (const xmlChar *) "pulselen")) != 0) {
      int plen = atoi((char *) n);
      if (plen != 0) {
        // Loop should be syncronized to a pulse of given length-
        (*new_loop)->pulse = CreatePulse(plen);
      }
      xmlFree(n);
    }
    
    xmlFreeDoc(ldat);
    // Don't call cleanup because another thread may have xml open
    // xmlCleanupParser();
  }

  return 0;
};

// Starts an interactive rename for a loop in memory
void LoopManager::RenameLoop(int loopid) {
  if (renamer == 0) {
    Loop *l = GetSlot(loopid);
    if (l != 0) {
      if (CRITTERS)
        printf("RENAME: Loop: %p\n",l);
      rename_loop = l;
      renamer = new ItemRenamer(app,this,l->name);
      if (!renamer->IsRenaming()) {
        delete renamer;
        renamer = 0;
        rename_loop = 0;
      }
    }
  }
};

void LoopManager::ItemRenamed(char *nw) {
  if (nw != 0) {
    // Rename on disk
    const static char *exts[] = {app->getCFG()->GetAudioFileExt(rename_loop->format), 
                                 FWEELIN_OUTPUT_DATA_EXT};
    char *old_filename = 0, 
      *new_filename = 0;
    rename_loop->RenameSaveable(app->getCFG()->GetLibraryPath(), 
                                FWEELIN_OUTPUT_LOOP_NAME,
                                rename_loop->name, nw,
                                exts, 2,
                                &old_filename,
                                &new_filename);
    
    // We also need to rename in the loop browser
    if (app->getBROWSER(B_Loop) != 0) 
      app->getBROWSER(B_Loop)->
        ItemRenamedOnDisk(old_filename,new_filename,nw);
    
    if (old_filename != 0)
      delete[] old_filename;
    if (new_filename != 0)
      delete[] new_filename;
    
    // Rename in memory
    RenameLoop(rename_loop,nw);

    // We have to notify the LoopTray of the new name given
    LoopTray *tray = (LoopTray *) app->getBROWSER(B_Loop_Tray);
    if (tray != 0)
      tray->ItemRenamedFromOutside(rename_loop,nw);
        
    delete renamer;
    renamer = 0;
    rename_loop = 0;
  } else {
    // Rename was aborted
    delete renamer;
    renamer = 0;
    rename_loop = 0;
  }
};

void LoopManager::GetWriteBlock(FILE **out, AudioBlock **b, 
                                AudioBlockIterator **i,
                                nframes_t *len) {
  // If we are autosaving, check that our list is up to date
  if (autosave)
    CheckSaveMap();

  // Do we have a loop to save?
  Event *cur = savequeue,
    *prev = 0;

  if (cursave >= numsave) {
    numsave = 0;
    cursave = 0;
  }

  int l_idx = 0;  
  char go = 1, advance = 1;
  while (cur != 0 && go) {
    if (cur->GetType() == T_EV_LoopList) {
      // Loop in save queue- does it exist and is it ready to save?
      if ((l_idx = app->getTMAP()->SearchMap(((LoopListEvent *) cur)->l)) == -1
          || GetStatus(l_idx) == T_LS_Overdubbing
          || GetStatus(l_idx) == T_LS_Recording) {
        if (l_idx == -1) {
          printf("DEBUG: Loop no longer exists- abort save!\n");
          EventManager::RemoveEvent(&savequeue,prev,&cur);
          advance = 0;
        }

        // If we are overdubbing or recording, just ignore this loop
        // we will come back to it
      } else {
        go = 0; // Found a suitable loop to save- stop!
        advance = 0;
      }
    } else {
      if (cur->GetType() == T_EV_SceneMarker) {
        // Scene marker in queue indicates we need to save a scene-
        if (cur == savequeue) {
          // No loops are waiting to be saved.. go
          app->getTMAP()->GoSave(((SceneMarkerEvent *) cur)->s_filename);
          EventManager::RemoveEvent(&savequeue,prev,&cur);
          cursave++;
          advance = 0;
        } 
      }
    }

    // Move to next item
    if (advance) {
      prev = cur; 
      cur = cur->next;
    }
    else 
      advance = 1;
  }

  if (cur != 0) {
    if (cur->GetType() != T_EV_LoopList) {
      printf("DISK: ERROR: LoopList event type mismatch!\n");
      EventManager::RemoveEvent(&savequeue,prev,&cur);
    } else {
      // Remove from list
      Loop *curl = ((LoopListEvent *) cur)->l;
      EventManager::RemoveEvent(&savequeue,prev,&cur);

      // Open up right files, save data & setup for audio save
      SetupSaveLoop(curl,l_idx,out,b,i,len);
      cursave++;
    }
  } else {
    // No loops to save right now
    *b = 0;
    *len = 0;
    *i = 0;
    if (*out != 0) {
      fclose(*out);
      *out = 0;
    }
  }
}

// We receive calls periodically for loading of loops-
void LoopManager::GetReadBlock(FILE **in, char *smooth_end) {
  if (curload >= numload) {
    numload = 0;
    curload = 0;
  }

  // Do we have a loop to load?
  Event *cur = loadqueue;
  if (cur != 0) {
    if (cur->GetType() == T_EV_LoopList) {
      // Open up right files, load data & setup for audio load
      LoopListEvent *ll = (LoopListEvent *) cur;
      if (SetupLoadLoop(in,smooth_end,
                        &ll->l,ll->l_idx,ll->l_vol,ll->l_filename)) {
        // Not a loop or there was an error in loading
        EventManager::RemoveEvent(&loadqueue,0,&cur);
        curload++;
      }
    } else {
      // Not a loop- remove
      EventManager::RemoveEvent(&loadqueue,0,&cur);
      curload++;
    }
  } else {
    // Nothing to load right now
    if (*in != 0) {
      printf("DISK: (Load) Nothing to load- close input!\n");
      fclose(*in);
      *in = 0;
    }
  }
}

void LoopManager::ReadComplete(AudioBlock *b) {
  curload++;

  // Add loop to triggermap and remove from load queue
  Event *cur = loadqueue;
  if (cur == 0 || cur->GetType() != T_EV_LoopList)
    printf("DISK: ERROR: Load list mismatch!\n");
  else {
    if (b == 0)
      printf("DISK: ERROR: .. during load!\n");
    else {
      LoopListEvent *ll = (LoopListEvent *) cur;

      // Put blocks into loop
      ll->l->blocks = b;

      if (app->getTMAP()->GetMap(ll->l_idx) != 0) {
        // Loop ID is full. Choose another
        int newidx = app->getTMAP()->GetFirstFree(default_looprange.lo,
                                                  default_looprange.hi);
        
        if (newidx != -1) {
          printf("LOOP MANAGER: LoopID #%d full, got new ID: #%d!\n",
                 ll->l_idx,newidx);
          ll->l_idx = newidx;
        } else {
          printf("LOOP MANAGER: No free loopids in default placement range.\n"
                 "I will erase the loop at id #%d.\n",ll->l_idx);
          DeleteLoop(ll->l_idx);
        }
      }

      // Add loop to our map
      app->getTMAP()->SetMap(ll->l_idx,ll->l);
      lastindex = ll->l_idx; // Set this so we can make a pulse from this loop
    }

    // And remove from load list
    EventManager::RemoveEvent(&loadqueue,0,&cur);
  }
}

void LoopManager::StripePulseOn(Pulse *pulse) {
  app->getBMG()->StripeBlockOn(pulse,app->getAMPEAKS(),
                               app->getAMPEAKSI());
  app->getBMG()->StripeBlockOn(pulse,app->getAUDIOMEM(),
                               app->getAUDIOMEMI());
}

void LoopManager::StripePulseOff(Pulse *pulse) {
  app->getBMG()->StripeBlockOff(pulse,app->getAMPEAKS());
  app->getBMG()->StripeBlockOff(pulse,app->getAUDIOMEM());
}

// Creates a pulse of the given length in the first available slot,
// if none already exists of the right length
Pulse *LoopManager::CreatePulse(nframes_t len) {
  // First, check to see if we have a pulse of the right length-
  int i;
  for (i = 0; i < MAX_PULSES && 
         (pulses[i] == 0 || pulses[i]->GetLength() != len); i++);
  if (i < MAX_PULSES)
    // Found it, use this pulse
    return pulses[i];
  else {
    // No pulse found of right length-- create a new one
    for (i = 0; i < MAX_PULSES && pulses[i] != 0; i++);
    if (i < MAX_PULSES) {
      app->getRP()->AddChild(pulses[i] = 
                             new Pulse(app,len,0),
                             ProcessorItem::TYPE_HIPRIORITY);
      StripePulseOn(pulses[i]);
      curpulseindex = i;

      // Send MIDI start for pulse
      GetCurPulse()->SetMIDIClock(1);
      
      return pulses[i];
    } else
      // No space for a new pulse!
      return 0;
  }
};

// Create a time pulse around the specified index
// The length of the loop on the specified index becomes
// a time constant around which other loops center themselves
// subdivide the length of the loop by subdivide to get the core pulse
void LoopManager::CreatePulse(int index, int pulseindex, int sub) {
  Loop *cur = app->getTMAP()->GetMap(index);
  if (cur != 0 && (status[index] == T_LS_Off ||
                   status[index] == T_LS_Playing ||
                   status[index] == T_LS_Overdubbing)) {
    // Set pulse length based on loop length
    nframes_t len = GetLength(index);
    if (len != 0) {
      // Create iterator
      len /= sub; // Length subdivide
      nframes_t startpos = 0;
      // So set the starting pulse position based on where loop is playing
      if (status[index] == T_LS_Playing)
        startpos = ((PlayProcessor *) plist[index])->GetPlayedLength() % len;
      else if (status[index] == T_LS_Overdubbing)
        startpos = ((RecordProcessor *) plist[index])->
          GetRecordedLength() % len;
      
      app->getRP()->AddChild(cur->pulse = pulses[pulseindex] = 
                             new Pulse(app,len,startpos),
                             ProcessorItem::TYPE_HIPRIORITY);
      StripePulseOn(cur->pulse);
      curpulseindex = pulseindex;
      cur->nbeats = sub; // Set # of beats in the loop

      // Send MIDI start for pulse
      GetCurPulse()->SetMIDIClock(1);
      
      // Now reconfigure processor on this index to be synced to the new pulse
      if (status[index] == T_LS_Playing) 
        ((PlayProcessor *) plist[index])->SyncUp();
      else if (status[index] == T_LS_Overdubbing)
        ((RecordProcessor *) plist[index])->SyncUp();
    }
  }
}

// Taps a pulse- starting at the downbeat- if newlen is nonzero, the pulse's
// length is adjusted to reflect the length between taps- and a new pulse
// is created if none exists
void LoopManager::TapPulse(int pulseindex, char newlen) {
  // If more than TIMEOUT_RATIO * the current pulse length
  // frames have passed since the last tap, a new length is not defined
  const static float TAP_NEWLEN_TIMEOUT_RATIO = 5.0, //2.0,
    // Higher graduation makes tempo more stable against changes
    TAP_NEWLEN_GRADUATION = 0.0, //0.5,
    // Tolerance for rejecting tap tempo changes- as fraction of current length
    TAP_NEWLEN_REJECT_TOLERANCE = 1.0; //0.3;

  if (pulseindex >= 0 || pulseindex < MAX_PULSES) {
    Pulse *cur = pulses[pulseindex];
    if (cur == 0) {
      if (newlen) {
        // New pulse- tap now!- set zero length for now
        cur = pulses[pulseindex] = new Pulse(app,0,0);
        cur->stopped = 1;
        cur->prevtap = app->getRP()->GetSampleCnt();
        //cur->SwitchMetronome(1);
        app->getRP()->AddChild(cur,ProcessorItem::TYPE_HIPRIORITY);
        
        StripePulseOn(cur);
        curpulseindex = pulseindex;
      }
    } else {
      // Test position of axis
      char nextdownbeat = 0;
      if (cur->GetPct() >= 0.5)
        nextdownbeat = 1;

      // Old pulse- tap now!
      if (newlen) {
        // Redefine length from tap
        nframes_t oldlen = cur->GetLength(),
          newtap = app->getRP()->GetSampleCnt(),
          newlen = newtap - cur->prevtap;

        // .. only if the new length isn't outrageous
        if (oldlen < 64)
          cur->SetLength(newlen);
        else if (newlen < oldlen * TAP_NEWLEN_TIMEOUT_RATIO) {
          // 2nd outrageous length check
          float ratio = (float) MIN(newlen,oldlen)/MAX(newlen,oldlen);
          if (ratio > 1.0-TAP_NEWLEN_REJECT_TOLERANCE)
            cur->SetLength((nframes_t) (oldlen*TAP_NEWLEN_GRADUATION +
                                        newlen*(1-TAP_NEWLEN_GRADUATION)));
        }

        cur->prevtap = newtap;
        //cur->SwitchMetronome(1);
        cur->stopped = 0;
      }

      if (nextdownbeat)
        // Tap to beginning- with wrap
        cur->Wrap();
      else
        // Tap to beginning- no wrap
        cur->SetPos(0);

      // Notify external transport that we have moved
      app->getAUDIO()->RelocateTransport(0);
    }
  } else
    printf("CORE: Invalid pulse #%d, ignoring.\n",pulseindex);
}

void LoopManager::SwitchMetronome(int pulseindex, char active) {
  if (pulseindex >= 0 || pulseindex < MAX_PULSES) {
    Pulse *cur = pulses[pulseindex];
    if (cur != 0)
      cur->SwitchMetronome(active);
    else
      printf("CORE: No pulse at #%d, ignoring.\n",pulseindex);
  } else
    printf("CORE: Invalid pulse #%d, ignoring.\n",pulseindex);
}

void LoopManager::DeletePulse(int pulseindex) {
  if (pulseindex < 0 || pulseindex >= MAX_PULSES) {
    printf("CORE: Invalid pulse #%d, ignoring.\n",pulseindex);
    return;
  }

  if (pulses[pulseindex] != 0) {
    // Stop striping beats from this pulse
    StripePulseOff(pulses[pulseindex]);

    // Erase all loops which are attached to this pulse-- or we'll have
    // references pointing to the deleted pulse
    int nt = app->getCFG()->GetNumTriggers();
    for (int i = 0; i < nt; i++)
      if (GetPulse(i) == pulses[pulseindex]) 
        DeleteLoop(i);

    // Erase this pulse
    app->getRP()->DelChild(pulses[pulseindex]);
    pulses[pulseindex] = 0;
  }
}

Pulse *LoopManager::GetPulse(int index) {
  Loop *lp = GetSlot(index);
  if (lp != 0)
    return lp->pulse;
  else
    return 0;
}

// Move the loop at specified index to another index
// only works if target index is empty
// returns 1 if success
int LoopManager::MoveLoop (int src, int tgt) {
  Loop *srloop = app->getTMAP()->GetMap(src);
  if (srloop != 0) {
    Loop *tgtloop = app->getTMAP()->GetMap(tgt);
    if (tgtloop == 0) {
      app->getTMAP()->SetMap(tgt,srloop);
      app->getTMAP()->SetMap(src,0);
      plist[tgt] = plist[src];
      plist[src] = 0;
      status[tgt] = status[src];
      status[src] = T_LS_Off;
      waitactivate[tgt] = waitactivate[src];
      waitactivate[src] = 0;
      waitactivate_shot[tgt] = waitactivate_shot[src];
      waitactivate_shot[src] = 0;
      waitactivate_vol[tgt] = waitactivate_vol[src];
      waitactivate_vol[src] = 0.;
      waitactivate_od[tgt] = waitactivate_od[src];
      waitactivate_od[src] = 0;
      waitactivate_od_fb[tgt] = waitactivate_od_fb[src];
      waitactivate_od_fb[src] = 0;
      for (int i = 0; i < LAST_REC_COUNT; i++)  
        if (lastrecidx[i] == src)
          lastrecidx[i] = tgt;

      if (lastindex == src)
        lastindex = tgt;
      
      UpdateLoopLists_ItemMoved(src,tgt);
    }
    else 
      return 0;
  }
  else
    return 0;
  
  return 1;
}

// Delete the loop at the specified index..
// Not RT safe!
// Threadsafe
void LoopManager::DeleteLoop (int index) {
  LockLoops();

  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp != 0) {
    // First, zero the map at the given index
    // To prevent anybody from attaching to the loop as we delete it
    app->getTMAP()->SetMap(index, 0);
  }

  if (plist[index] != 0) {
    // We have a processor on this loop! Stop it!
    if (status[index] == T_LS_Recording) {
      RecordProcessor *recp = (RecordProcessor *) plist[index];
      recp->AbortRecording();
      AudioBlock *recblk = recp->GetFirstRecordedBlock();
      if (recblk != 0) {
        app->getBMG()->RefDeleted(recblk);
        recblk->DeleteChain(); // *** Not RT Safe
        if (lp != 0)
          lp->blocks = 0;
      }

      numrecordingloops--;
    } else if (status[index] == T_LS_Overdubbing)
      numrecordingloops--;

    // Remove the record/play processor
    app->getRP()->DelChild(plist[index]);
    plist[index] = 0;
    status[index] = T_LS_Off;
    waitactivate[index] = 0;
    waitactivate_shot[index] = 0;
    waitactivate_vol[index] = 0.;
    waitactivate_od[index] = 0;
    waitactivate_od_fb[index] = 0;
  }
    
  if (lp != 0) {
    if (lp->blocks != 0) {
      // Notify any blockmanagers working on this loop's audio to end!
      app->getBMG()->RefDeleted(lp->blocks);
      lp->blocks->DeleteChain(); // *** Not RT Safe
    }

    delete lp;                   // *** Not RT Safe
    numloops--;
    
    // Update looplists/scenes to ensure that loop is removed from them
    UpdateLoopLists_ItemRemoved(index);
  }

  UnlockLoops();
}

void LoopManager::UpdateLoopLists_ItemAdded (int l_idx) {
  // Update...

  // Snapshots
  Snapshot *snaps = app->getSNAPS();
  for (int i = 0; i < app->getCFG()->GetMaxSnapshots(); i++) {
    if (snaps[i].exists) {
      Snapshot *s = &snaps[i];
      char go = 1;
      for (int j = 0; go && j < s->numls; j++) 
        if (s->ls[j].l_idx == l_idx)
          go = 0;

      if (go) {
        // Loop index not present in snapshot- add, defaulting to loop off
        LoopSnapshot *newls = 0;
        newls = new LoopSnapshot[s->numls+1];

        memcpy(newls,s->ls,sizeof(LoopSnapshot) * s->numls);
        LoopSnapshot *n = &newls[s->numls];

        n->l_idx = l_idx;
        n->status = T_LS_Off;
        n->l_vol = GetLoopVolume(l_idx);
        n->t_vol = 0.;

        delete[] s->ls;
        s->ls = newls;
        s->numls = s->numls+1;
      }
    }
  }
};

void LoopManager::UpdateLoopLists_ItemRemoved (int l_idx) {
  // Update...

  // Selection sets
  for (int i = 0; i < NUM_LOOP_SELECTION_SETS; i++) {
    LoopList **ll = app->getLOOPSEL(i);
    *ll = LoopList::Remove(*ll,l_idx);
  }

  // Snapshots
  Snapshot *snaps = app->getSNAPS();
  for (int i = 0; i < app->getCFG()->GetMaxSnapshots(); i++) {
    if (snaps[i].exists) {
      Snapshot *s = &snaps[i];
      char go = 1;
      for (int j = 0; go && j < s->numls; j++) 
        if (s->ls[j].l_idx == l_idx) {
          // Remove loop from list
          LoopSnapshot *newls = 0;
          if (s->numls > 1) {
            newls = new LoopSnapshot[s->numls-1];

            // All elements preceding j
            memcpy(newls,s->ls,sizeof(LoopSnapshot) * j);
            // & following
            memcpy(&newls[j],&(s->ls[j+1]),
                   sizeof(LoopSnapshot) * (s->numls-j-1));
          }

          delete[] s->ls;
          s->ls = newls;
          s->numls = s->numls-1;
          go = 0; // No more checking in this snapshot
        }
    }
  }
};

void LoopManager::UpdateLoopLists_ItemMoved (int l_idx_old, int l_idx_new) {
  // Update...

  // Selection sets
  for (int i = 0; i < NUM_LOOP_SELECTION_SETS; i++) {
    LoopList **ll = app->getLOOPSEL(i),
      *prev,
      *found = LoopList::Scan(*ll,l_idx_old,&prev);
    
    // Update index
    if (found != 0)
      found->l_idx = l_idx_new;
  }

  // Snapshots
  Snapshot *snaps = app->getSNAPS();
  for (int i = 0; i < app->getCFG()->GetMaxSnapshots(); i++) {
    if (snaps[i].exists) {
      Snapshot *s = &snaps[i];
      for (int j = 0; j < s->numls; j++) 
        if (s->ls[j].l_idx == l_idx_old)
          s->ls[j].l_idx = l_idx_new;
    }
  }
};

// Trigger the loop at index within the map
// The exact behavior varies depending on what is already happening with
// this loop and the settings passed- see .fweelin.rc
// *** Not RT Safe
void LoopManager::Activate (int index, char shot, float vol, nframes_t ofs, 
                            char overdub, float *od_feedback) {
  // printf("ACTIVATE plist %p status %d\n",plist[index],status[index]);

  if (plist[index] != 0) {
    // We have a problem, we already have a processor on this index.
    // Queue the requested activate
    waitactivate[index] = 1;
    waitactivate_shot[index] = shot;
    waitactivate_vol[index] = vol;
    waitactivate_od[index] = overdub;
    waitactivate_od_fb[index] = od_feedback;
    return;
  }
  
  Loop *lp = app->getTMAP()->GetMap(index);
  if (lp == 0) {
    // Record a new loop
    float *inputvol = &(app->getRP()->inputvol); // Where to get input vol from
    app->getRP()->AddChild(plist[index] =
                           new RecordProcessor(app,app->getISET(),inputvol,
                                               GetCurPulse(),
                                               app->getAUDIOMEM(),
                                               app->getAUDIOMEMI(),
                                               app->getCFG()->
                                               loop_peaksavgs_chunksize));
    
    numrecordingloops++;
    status[index] = T_LS_Recording;
    // Keep track of this index in our record of last recorded indexes
    for (int i = LAST_REC_COUNT-1; i > 0; i--)
      lastrecidx[i] = lastrecidx[i-1];
    lastrecidx[0] = index;
  } else {
    // A loop exists at that index
    if (overdub) {
      // Overdub
      float *inputvol = &(app->getRP()->inputvol); // Get input vol from main
      app->getRP()->AddChild(plist[index] = 
                             new RecordProcessor(app,
                                                 app->getISET(),inputvol,
                                                 lp,vol,ofs,od_feedback));
      numrecordingloops++;
      status[index] = T_LS_Overdubbing;
    } else {
      // Play
      app->getRP()->AddChild(plist[index] = 
                             new PlayProcessor(app,lp,vol,ofs));
      status[index] = T_LS_Playing;
    }
  }
}

// *** Not RT Safe
void LoopManager::Deactivate (int index) {
  if (plist[index] == 0) {
    // We have a problem, there is supposed to be a processor here!
    printf("Nothing happening on index %d to deactivate\n",index);
    return;
  }
  
  // If we recorded something new to this index, store it in the map
  if (status[index] == T_LS_Recording && 
      app->getTMAP()->GetMap(index) == 0) {
    // *** Perhaps make a function in RecordProcessor called
    // ** 'createloop'.. which does the encapsulation from the blocks
    Pulse *curpulse = 0;
    if (curpulseindex != -1)
      curpulse = pulses[curpulseindex];

    // Adjust newloop volume so that it will match the volume
    // it was heard as-- since output volume does not scale
    // the initial monitor but does scale loops, we need to adjust
    float adjustednewloopvol = newloopvol / GetOutputVolume(); 

    //printf("newlp from plist: %p\n",plist[index]);
    Loop *newlp = new
      Loop(((RecordProcessor *) plist[index])->GetFirstRecordedBlock(),
           curpulse,1.0,adjustednewloopvol,
           ((RecordProcessor *) plist[index])->GetNBeats(),
           app->getCFG()->GetLoopOutFormat());
    app->getTMAP()->SetMap(index, newlp);
    UpdateLoopLists_ItemAdded(index);
    numloops++;
    lastindex = index;

    // Record processor will broadcast when it is ready to end!
    ((RecordProcessor *) plist[index])->End();
  } else if (status[index] == T_LS_Overdubbing) {
    // Overdubbing record processor will end immediately and broadcast 
    // EndRecord event
    ((RecordProcessor *) plist[index])->End();
  } else if (status[index] == T_LS_Playing) {
    // Stop playing/overdubbing
    app->getRP()->DelChild(plist[index]);
    plist[index] = 0;
    status[index] = T_LS_Off;    
  }
}

void LoopManager::SaveLoop(int index) {
  Loop *l = app->getTMAP()->GetMap(index);
  if (l != 0)
    l->Save(app);
};

// Saves a new scene
void LoopManager::SaveNewScene() {
  TriggerMap *tm = app->getTMAP();
  if (tm != 0)
    tm->Save(app);
};

// Saves over current scene
void LoopManager::SaveCurScene() {
  if (app->getCURSCENE() == 0)
    SaveNewScene();
  else {
    TriggerMap *tm = app->getTMAP();
    if (tm != 0)
      tm->Save(app,app->getCURSCENE()->filename);
  }
};

// Load loop from disk into the given index
void LoopManager::LoadLoop(char *filename, int index, float vol) {
  AddLoopToLoadQueue(filename,index,vol);
};

// Load scene from disk
void LoopManager::LoadScene(SceneBrowserItem *i) {
  char *filename = i->filename;

  // Load XML data for scene
  char tmp[FWEELIN_OUTNAME_LEN],
    tmp2[FWEELIN_OUTNAME_LEN];
  snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s%s",
           filename,FWEELIN_OUTPUT_DATA_EXT);
  
  xmlDocPtr dat = xmlParseFile(tmp);
  if (dat == 0)
    printf("DISK: ERROR: Scene data '%s' invalid or missing!\n",tmp);
  else {
    xmlNode *root = xmlDocGetRootElement(dat);
    if (!root || !root->name ||
        xmlStrcmp(root->name,(const xmlChar *) FWEELIN_OUTPUT_SCENE_NAME))
      printf("DISK: ERROR: Scene data '%s' bad format!\n",tmp);
    else {
      for (xmlNode *cur_node = root->children; cur_node != NULL; 
           cur_node = cur_node->next) {
        if ((!xmlStrcmp(cur_node->name, 
                        (const xmlChar *) FWEELIN_OUTPUT_LOOP_NAME))) {
          // Loop within scene-- read
          int l_idx = loadloopid;
          float vol = 1.0;

          // Loopid
          xmlChar *n = xmlGetProp(cur_node, (const xmlChar *) "loopid");
          if (n != 0) {
            l_idx = atoi((char *) n);
            xmlFree(n);
          }

          // Volume
          if ((n = xmlGetProp(cur_node, (const xmlChar *) "volume")) != 0) {
            vol = atof((char *) n);
            xmlFree(n);
          }

          // Hash
          if ((n = xmlGetProp(cur_node, (const xmlChar *) "hash")) != 0) {
            // Compose loop filename from hash
            snprintf(tmp2,FWEELIN_OUTNAME_LEN,"%s/%s-%s",
                     app->getCFG()->GetLibraryPath(),
                     FWEELIN_OUTPUT_LOOP_NAME,n);
            xmlFree(n);

            // Load the loop into the specified index
            printf(" (loopid %d vol %.5f filename %s)\n",
                   l_idx,vol,tmp2);
            LoadLoop(tmp2,l_idx,vol);
            // sleep(2);
          } else 
            printf("DISK: Scene definition for loop (id %d) has missing "
                   "hash!\n",l_idx);
        } else if ((!xmlStrcmp(cur_node->name, 
                               (const xmlChar *) FWEELIN_OUTPUT_SNAPSHOT_NAME))) {
          // Snapshot within scene-- read
          int snapid = 0;
          char sgo = 1;

          // Snapshot index
          xmlChar *n = xmlGetProp(cur_node, (const xmlChar *) "snapid");
          if (n != 0) {
            snapid = atoi((char *) n);
            xmlFree(n);
          }

          // Check if snapshot exists- if so, find another slot
          if (app->getSNAP(snapid) == 0 || app->getSNAP(snapid)->exists) {
            Snapshot *snaps = app->getSNAPS();
            char go = 1;
            int i = 0; 
            while (go && i < app->getCFG()->GetMaxSnapshots()) {
              if (!snaps[i].exists) 
                go = 0;
              else
                i++;
            }
            
            if (go) {
              printf("DISK: No space to load snapshot in scene-\n"
                     "please raise maximum # of snapshots in configuration!\n");
              sgo = 0;
            } else
              snapid = i;
          }

          if (sgo) {
            // Name
            n = xmlGetProp(cur_node, (const xmlChar *) "name");

            printf(" (snapshot: %s)\n",n);
            Snapshot *s = app->LoadSnapshot(snapid,(char *) n);
            if (n != 0)
              xmlFree(n);

            // Now, count loop snapshots given in snapshot
            if (s != 0) {
              int numls = 0;
              for (xmlNode *ls_node = cur_node->children; ls_node != NULL; 
                   ls_node = ls_node->next) {
                if ((!xmlStrcmp(ls_node->name, 
                                (const xmlChar *) FWEELIN_OUTPUT_LOOPSNAPSHOT_NAME))) {
                  numls++;
                }
              }
              
              printf("  (%d loops in snapshot)\n",numls);

              // Setup & load loop snapshots
              s->numls = numls;
              if (numls > 0)
                s->ls = new LoopSnapshot[numls];
              else
                s->ls = 0;

              int i = 0;
              for (xmlNode *ls_node = cur_node->children; ls_node != NULL; 
                   ls_node = ls_node->next) {
                if ((!xmlStrcmp(ls_node->name, 
                                (const xmlChar *) FWEELIN_OUTPUT_LOOPSNAPSHOT_NAME))) {
                  LoopSnapshot *ls = &(s->ls[i]);

                  // Loop index
                  xmlChar *nn = xmlGetProp(ls_node, (const xmlChar *) "loopid");
                  if (nn != 0) {
                    ls->l_idx = atoi((char *) nn);
                    xmlFree(nn);
                  }

                  // Loop status
                  nn = xmlGetProp(ls_node, (const xmlChar *) "status");
                  if (nn != 0) {
                    ls->status = (LoopStatus) atoi((char *) nn);
                    xmlFree(nn);
                  }

                  // Loop volume
                  nn = xmlGetProp(ls_node, (const xmlChar *) "loopvol");
                  if (nn != 0) {
                    ls->l_vol = atof((char *) nn);
                    xmlFree(nn);
                  }

                  // Trigger volume
                  nn = xmlGetProp(ls_node, (const xmlChar *) "triggervol");
                  if (nn != 0) {
                    ls->t_vol = atof((char *) nn);
                    xmlFree(nn);
                  }

                  i++;
                }
              }
            }
          }
        }
      }

      // Now, remember this scene is loaded
      app->setCURSCENE(i);
    }
  }

  xmlFreeDoc(dat);
  // Don't call cleanup because another thread may have xml open
  // xmlCleanupParser();
};

void LoopManager::ReceiveEvent(Event *ev, EventProducer *from) {
  switch (ev->GetType()) {
  case T_EV_EndRecord :
    // Recording has ended on one of the RecordProcessors- find it!
    for (int i = 0; i < app->getTMAP()->GetMapSize(); i++) 
      if (plist[i] == from) {
        // Should we keep this recording
        if (!((EndRecordEvent *) ev)->keeprecord) {
          DeleteLoop(i); // No
        }
        else {
          nframes_t playofs = 0;
          if (status[i] == T_LS_Recording) {
            // Adjust number of beats in loop based on the recording
            app->getTMAP()->GetMap(i)->nbeats = 
              ((RecordProcessor *) plist[i])->GetNBeats();

            Pulse *recsync = ((RecordProcessor *) plist[i])->GetPulse();
            // Sync recording may have ended late, so start play where we
            // left off
            if (recsync != 0)
              playofs = recsync->GetPos();
          } else if (status[i] == T_LS_Overdubbing) {
            // Start play at position where overdub left off
            playofs = ((RecordProcessor *) plist[i])->GetRecordedLength();
          }

          // Remove recordprocessor from chain
          app->getRP()->DelChild(plist[i]);
          numrecordingloops--;
          status[i] = T_LS_Off;
          plist[i] = 0;

          // Check if we need to activate a playprocessor
          if (waitactivate[i]) {
            waitactivate[i] = 0;
            // Activate is not RT safe (new processor alloc)
            // So this event thread had better be nonRT!
            Activate(i,waitactivate_shot[i],waitactivate_vol[i],
                     playofs,
                     waitactivate_od[i],waitactivate_od_fb[i]);
          }
        }
      }
    break;

  case T_EV_ToggleDiskOutput :
    {
      // OK!
      if (CRITTERS)
        printf("CORE: Received ToggleDiskOutputEvent\n");
      app->ToggleDiskOutput();
    }
    break;

  case T_EV_ToggleSelectLoop :
    {
      ToggleSelectLoopEvent *sev = (ToggleSelectLoopEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received ToggleSelectLoopEvent: Set %d Loop ID %d\n",
               sev->setid,sev->loopid);
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        // Get loop with id
        Loop *l = app->getTMAP()->GetMap(sev->loopid);
        if (l != 0) {
          LoopList *prev;
          LoopList *exists = LoopList::Scan(*ll,sev->loopid,&prev);
          if (exists != 0) {
            // printf("REMOVE!\n");
            *ll = LoopList::Remove(*ll,exists,prev);
            l->ChangeSelectedCount(-1);
          } else {
            // printf("ADD!\n");
            *ll = LoopList::AddBegin(*ll,sev->loopid);
            l->ChangeSelectedCount(1);
          }
        }
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_SelectOnlyPlayingLoops :
    {
      SelectOnlyPlayingLoopsEvent *sev = (SelectOnlyPlayingLoopsEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SelectOnlyPlayingLoopsEvent: Set %d [%s]\n",
               sev->setid,(sev->playing ? "PLAYING" : "IDLE"));
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        // Scan all loops for playing loops
        for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) {
          Loop *l = app->getTMAP()->GetMap(i);
          if (GetStatus(i) == T_LS_Overdubbing ||
              GetStatus(i) == T_LS_Playing) {
            if (l != 0) {
              // Loop exists, and it's playing!
              LoopList *prev;
              LoopList *exists = LoopList::Scan(*ll,i,&prev);
              if (!sev->playing && exists != 0) {
                // printf("REMOVE!\n");
                *ll = LoopList::Remove(*ll,exists,prev);
                l->ChangeSelectedCount(-1);
              } else if (sev->playing && exists == 0) {
                // printf("ADD!\n");
                *ll = LoopList::AddBegin(*ll,i);
                l->ChangeSelectedCount(1);
              }
            }
          } else if (app->getTMAP()->GetMap(i) != 0) {
            // Loop exists, but not playing/overdubbing
            LoopList *prev;
            LoopList *exists = LoopList::Scan(*ll,i,&prev);
            if (sev->playing && exists != 0) {
              // printf("REMOVE!\n");
              *ll = LoopList::Remove(*ll,exists,prev);
              l->ChangeSelectedCount(-1);
            } else if (!sev->playing && exists == 0) {
              // printf("ADD!\n");
              *ll = LoopList::AddBegin(*ll,i);
              l->ChangeSelectedCount(1);
            }
          }
        }
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_SelectAllLoops :
    {
      SelectAllLoopsEvent *sev = (SelectAllLoopsEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SelectAllLoopsEvent: Set %d [%s]\n",
               sev->setid,(sev->select ? "SELECT" : "UNSELECT"));
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        // Scan all loops
        for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) {
          Loop *l = app->getTMAP()->GetMap(i);
          if (l != 0) {
            // Loop exists in map
            LoopList *prev;
            LoopList *exists = LoopList::Scan(*ll,i,&prev);
            if (!sev->select && exists != 0) {
              // Unselect loops- remove loop from list
              // printf("REMOVE!\n");
              *ll = LoopList::Remove(*ll,exists,prev);
              l->ChangeSelectedCount(-1);
            } else if (sev->select && exists == 0) {
              // Select loops- add loop to list
              // printf("ADD!\n");
              *ll = LoopList::AddBegin(*ll,i);
              l->ChangeSelectedCount(1);
            }
          }
        }
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_InvertSelection :
    {
      InvertSelectionEvent *sev = (InvertSelectionEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received InvertSelectionEvent: Set %d\n",sev->setid);

      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        // Scan all loops
        for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) {
          Loop *l = app->getTMAP()->GetMap(i);
          if (l != 0) {
            // Loop exists in map
            LoopList *prev;
            LoopList *exists = LoopList::Scan(*ll,i,&prev);
            if (exists != 0) {
              // Loop exists in list- remove
              // printf("REMOVE!\n");
              *ll = LoopList::Remove(*ll,exists,prev);
              l->ChangeSelectedCount(-1);
            } else if (exists == 0) {
              // Loop not in list- add
              // printf("ADD!\n");
              *ll = LoopList::AddBegin(*ll,i);
              l->ChangeSelectedCount(1);
            }
          }
        }
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_TriggerSnapshot :
    {
      TriggerSnapshotEvent *sev = (TriggerSnapshotEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received TriggerSnapshotEvent: Snapshot #%d\n",
               sev->snapid);

      if (app->TriggerSnapshot(sev->snapid))
        printf("CORE: Invalid snapshot #%d- can't trigger\n",sev->snapid);
    }
    break;

  case T_EV_CreateSnapshot :
    {
      CreateSnapshotEvent *sev = (CreateSnapshotEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received CreateSnapshotEvent: Snapshot #%d\n",
               sev->snapid);

      if (app->CreateSnapshot(sev->snapid) == 0)
        printf("CORE: Invalid snapshot #%d- can't create\n",sev->snapid);
    }
    break;

  case T_EV_RenameSnapshot :
    {
      RenameSnapshotEvent *sev = (RenameSnapshotEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received RenameSnapshotEvent: Snapshot #%d\n",
               sev->snapid);

      FloDisplaySnapshots *sdisp = (FloDisplaySnapshots *) app->getCFG()->GetDisplayByType(FD_Snapshots);
      if (sdisp != 0)
        sdisp->Rename(sev->snapid);
    }
    break;

  case T_EV_SetSelectedLoopsTriggerVolume :
    {
      SetSelectedLoopsTriggerVolumeEvent *sev = (SetSelectedLoopsTriggerVolumeEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received SetSelectedLoopsTriggerVolumeEvent: Set %d: Volume %f\n",
               sev->setid,sev->vol);
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        LoopList *cur = *ll;
        while (cur != 0) {
          SetTriggerVol(cur->l_idx,sev->vol);
          cur = cur->next;
        }
        
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_AdjustSelectedLoopsAmp :
    {
      AdjustSelectedLoopsAmpEvent *sev = (AdjustSelectedLoopsAmpEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received AdjustSelectedLoopsAmpEvent: Set %d: "
               "Amp factor %f\n",
               sev->setid,sev->ampfactor);
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        LoopList *cur = *ll;
        while (cur != 0) {
          SetLoopVolume(cur->l_idx,
                        sev->ampfactor * GetLoopVolume(cur->l_idx));
          cur = cur->next;
        }
        
      } else 
        printf("CORE: Invalid set id #%d when selecting loop\n",sev->setid);
    }
    break;

  case T_EV_EraseSelectedLoops :
    {
      EraseSelectedLoopsEvent *sev = (EraseSelectedLoopsEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received EraseSelectedLoopsEvent: Set: %d\n",sev->setid);
      
      LoopList **ll = app->getLOOPSEL(sev->setid);
      if (ll != 0) {
        LoopList *cur = *ll;
        while (cur != 0) {
          DeleteLoop(cur->l_idx);
          cur = cur->next;
        }       
      } else 
        printf("CORE: Invalid set id #%d when erasing selected loops\n",
               sev->setid);
    }
    break;
    
  case T_EV_SetAutoLoopSaving :
    {
      SetAutoLoopSavingEvent *sev = (SetAutoLoopSavingEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetAutoLoopSavingEvent (%s)\n",
               (sev->save ? "on" : "off"));
      SetAutoLoopSaving(sev->save);
    }
    break;

  case T_EV_SaveLoop :
    {
      SaveLoopEvent *sev = (SaveLoopEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SaveLoopEvent (%d)\n",sev->index);
      SaveLoop(sev->index);
    }
    break;

  case T_EV_SaveNewScene :
    {
      // OK!
      if (CRITTERS)
        printf("CORE: Received SaveNewSceneEvent\n");
      SaveNewScene();
    }
    break;

  case T_EV_SaveCurrentScene :
    {
      // OK!
      if (CRITTERS)
        printf("CORE: Received SaveCurrentSceneEvent\n");
      SaveCurScene();
    }
    break;
    
  case T_EV_SetLoadLoopId :
    {
      SetLoadLoopIdEvent *sev = (SetLoadLoopIdEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetLoadLoopIdEvent (%d)\n",sev->index);
      loadloopid = sev->index;
    }
    break;

  case T_EV_SetDefaultLoopPlacement :
    {
      SetDefaultLoopPlacementEvent *sev = (SetDefaultLoopPlacementEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetDefaultLoopPlacementEvent (%d>%d)\n",
               sev->looprange.lo,sev->looprange.hi);
      default_looprange = sev->looprange;
    }
    break;

  case T_EV_SlideMasterInVolume :
    {
      SlideMasterInVolumeEvent *vev = (SlideMasterInVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SlideMasterInVolumeEvent(%f)\n", vev->slide);
      AdjustInputVolume(vev->slide);
    }
    break;

  case T_EV_SlideMasterOutVolume :
    {
      SlideMasterOutVolumeEvent *vev = (SlideMasterOutVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SlideMasterOutVolumeEvent(%f)\n", vev->slide);
      AdjustOutputVolume(vev->slide);
    }
    break;

  case T_EV_SlideInVolume :
    {
      SlideInVolumeEvent *vev = (SlideInVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SlideInVolumeEvent(%d: %f)\n", vev->input, vev->slide);
      app->getISET()->AdjustInputVol(vev->input-1, vev->slide);
    }
    break;

  case T_EV_SetMasterInVolume :
    {
      SetMasterInVolumeEvent *vev = (SetMasterInVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetMasterInVolumeEvent(%f, %f)\n", vev->vol, vev->fadervol);
      SetInputVolume(vev->vol,vev->fadervol);
    }
    break;

  case T_EV_SetMasterOutVolume :
    {
      SetMasterOutVolumeEvent *vev = (SetMasterOutVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetMasterOutVolumeEvent(%f, %f)\n", vev->vol, vev->fadervol);
      SetOutputVolume(vev->vol,vev->fadervol);
    }
    break;

  case T_EV_SetInVolume :
    {
      SetInVolumeEvent *vev = (SetInVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetInVolumeEvent(%d: %f, %f)\n", vev->input, vev->vol, vev->fadervol);
      app->getISET()->SetInputVol(vev->input-1, vev->vol, vev->fadervol);
    }
    break;

  case T_EV_ToggleInputRecord :
    {
      ToggleInputRecordEvent *vev = (ToggleInputRecordEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received ToggleInputRecordEvent(%d)\n", vev->input);
      app->getISET()->SelectInput(vev->input-1,(app->getISET()->InputSelected(vev->input-1) == 0 ? 1 : 0));
    }
    break;

  case T_EV_DeletePulse :
    {
      DeletePulseEvent *dev = (DeletePulseEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received DeletePulse(%d)\n", dev->pulse);
      DeletePulse(dev->pulse);
    }
    break;

  case T_EV_SelectPulse :
    {
      SelectPulseEvent *sev = (SelectPulseEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SelectPulse(%d)\n", sev->pulse);
      SelectPulse(sev->pulse);
    }
    break;

  case T_EV_TapPulse :
    {
      TapPulseEvent *tev = (TapPulseEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received TapPulse(%d) %s\n", tev->pulse,
               (tev->newlen ? "[new length]" : ""));
      TapPulse(tev->pulse,tev->newlen);
    }
    break;

  case T_EV_SwitchMetronome :
    {
      SwitchMetronomeEvent *swev = (SwitchMetronomeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SwitchMetronome(%d) %s\n", swev->pulse,
               (swev->metronome ? "[on]" : "[off]"));
      SwitchMetronome(swev->pulse,swev->metronome);
    }
    break;

  case T_EV_SetSyncType :
    {
      SetSyncTypeEvent *sev = (SetSyncTypeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetSyncType(%d)\n", sev->stype);
      app->SetSyncType(sev->stype);
    }
    break;

  case T_EV_SetSyncSpeed :
    {
      SetSyncSpeedEvent *sev = (SetSyncSpeedEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetSyncSpeed(%d)\n", sev->sspd);
      app->SetSyncSpeed(sev->sspd);
    }
    break;

  case T_EV_SetMidiSync :
    {
      SetMidiSyncEvent *sev = (SetMidiSyncEvent *) ev;
      
      // OK!
      if (CRITTERS)
        printf("CORE: Received SetMidiSync(%d)\n", sev->midisync);
      app->getMIDI()->SetMIDISyncTransmit(sev->midisync);
    }
    break;
    
  case T_EV_SetTriggerVolume :
    {
      SetTriggerVolumeEvent *laev = (SetTriggerVolumeEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetTriggerVolume(%d,%f)\n", laev->index, 
               laev->vol);
      SetTriggerVol(laev->index,laev->vol);
    }
    break;

  case T_EV_SlideLoopAmp :
    {
      SlideLoopAmpEvent *laev = (SlideLoopAmpEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SlideLoopAmp(%d,%f)\n", laev->index, 
               laev->slide);
      AdjustLoopVolume(laev->index,laev->slide);
    }
    break;

  case T_EV_SetLoopAmp :
    {
      SetLoopAmpEvent *laev = (SetLoopAmpEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received SetLoopAmp(%d,%f)\n", laev->index, laev->amp);
      SetLoopVolume(laev->index,laev->amp);
    }
    break;

  case T_EV_AdjustLoopAmp :
    {
      AdjustLoopAmpEvent *laev = (AdjustLoopAmpEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received AdjustLoopAmp(%d,%f)\n", laev->index, 
               laev->ampfactor);
      SetLoopVolume(laev->index,
                    laev->ampfactor * GetLoopVolume(laev->index));
    }
    break;

  case T_EV_TriggerLoop :
    {
      TriggerLoopEvent *tev = (TriggerLoopEvent *) ev;
      int index = tev->index,
        engage = tev->engage;
      float vol = tev->vol;
      char od = tev->od,
        shot = tev->shot;
      UserVariable *od_fb = tev->od_fb;
      float *od_fb_ptr = 0;
      if (od_fb != 0) {
        if (od_fb->GetType() == T_float)
          od_fb_ptr = (float *) od_fb->GetValue();
        else 
          printf("CORE: ERROR: Overdub feedback assigned to variable '%s'- but that variable is not a 'float'!\n",od_fb->GetName());
      }
      
      // OK!
      if (CRITTERS) {
        printf("CORE: Received TriggerLoop(%d,%.2f)", index, vol);
        if (od) {
          printf(" [overdub]");
          if (od_fb != 0) {
            printf(" (feedback ");
            od_fb->Print();
            printf(")\n");
          } else
            printf("\n");
        }
        if (shot)
          printf(" (shot)");
        if (engage != -1)
          printf(" (%s)\n",(engage ? "force on" : "force off"));
        else
          printf("\n");
      }

      if ((engage == -1 || engage == 1) &&
          (GetStatus(index) == T_LS_Recording || 
           GetStatus(index) == T_LS_Overdubbing ||
           (GetStatus(index) == T_LS_Playing && od == 1))) {
        // Stop-start case
        nframes_t ofs = 0;
        if (GetStatus(index) == T_LS_Overdubbing && od == 1) {
          // Don't allow retrigger from overdub to overdub-- override to play
          od = 0;
        } else if (GetStatus(index) == T_LS_Playing) {
          // Play->overdub case- start overdub where play left off
          ofs = ((PlayProcessor *) plist[index])->GetPlayedLength();
        }

        Deactivate(index);                // Stop
        Activate(index,shot,vol,ofs,od,od_fb_ptr); // Start
      } else if ((engage == -1 || engage == 0) && IsActive(index)) {
        // Stop case (play and no overdub)
        Deactivate(index);
      }
      else if (engage == -1 || engage == 1) {
        // Start case (record)
        Activate(index,shot,vol,0,od,od_fb_ptr);
      }
    }
    break;

  case T_EV_TriggerSelectedLoops :
    {
      TriggerSelectedLoopsEvent *tev = (TriggerSelectedLoopsEvent *) ev;

      if (CRITTERS)
        printf("CORE: Received TriggerSelectedLoops(set #%d,%.2f)\n", 
               tev->setid,tev->vol);

      LoopList **ll = app->getLOOPSEL(tev->setid);
      if (ll != 0) {
        // Get all loops from this set
        LoopList *cur = *ll;
        while (cur != 0) {
          if (IsActive(cur->l_idx)) {
            // Overdub/play on this loop
            if (tev->toggleloops)
              Deactivate(cur->l_idx);
          } else {
            // Loop idle-- start play
            // No overdub/shot/etc, just straight play
            Activate(cur->l_idx,0,tev->vol,0,0,0);
          }

          cur = cur->next;
        }
      } else 
        printf("CORE: Invalid set id #%d when triggering selected loops\n",
               tev->setid);      
    }
    break;

  case T_EV_MoveLoop :
    {
      MoveLoopEvent *mev = (MoveLoopEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received MoveLoop(%d->%d)\n", mev->oldloopid, 
               mev->newloopid);
      MoveLoop(mev->oldloopid,mev->newloopid);
    }
    break;

  case T_EV_RenameLoop :
    {
      RenameLoopEvent *rev = (RenameLoopEvent *) ev;

      if (rev->in == 1) {
        RenameLoop(rev->loopid);
        if (CRITTERS)
          printf("LOOPMGR: Received RenameLoop(loopid: %d)\n",rev->loopid);
      }
    }
    break;

  case T_EV_EraseLoop :
    {
      EraseLoopEvent *eev = (EraseLoopEvent *) ev;

      // OK!
      if (CRITTERS)
        printf("CORE: Received EraseLoop(%d)\n", eev->index);
      DeleteLoop(eev->index);
    }
    break;

  case T_EV_EraseAllLoops :
    {
      // OK!
      if (CRITTERS)
        printf("CORE: Received EraseAllLoops\n");

      // Erase scene settings
      app->setCURSCENE(0);

      // Erase all loops!
      // printf("DEBUG: ERASE LOOPS!\n");
      for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) 
        DeleteLoop(i);
      // And all pulses!
      // printf("DEBUG: ERASE PULSES!\n");
      for (int i = 0; i < MAX_PULSES; i++)
        DeletePulse(i);
      // printf("DEBUG: DONE!\n\n");
      // And all snapshots!
      Snapshot *s = app->getSNAPS();
      for (int i = 0; i < app->getCFG()->GetMaxSnapshots(); i++)
        s[i].DeleteSnapshot();
    }
    break;

  case T_EV_SlideLoopAmpStopAll :
    {
      // OK!
      if (CRITTERS)
        printf("CORE: Received SlideLoopAmpStopAll\n");

      for (int i = 0; i < app->getCFG()->GetNumTriggers(); i++) 
        SetLoopdVolume(i,1.0);
    }
    break;

  default:
    break;
  }
}

int Fweelin::go()
{
  running = 1;

  // Broadcast start session event!
  Event *proto = Event::GetEventByType(T_EV_StartSession);
  if (proto == 0) {
    printf("GO: Can't get start event prototype!\n");
  } else {
    Event *cpy = (Event *) proto->RTNew();
    if (cpy == 0)
      printf("CORE: WARNING: Can't send event- RTNew() failed\n");
    else 
      emg->BroadcastEventNow(cpy, this);
  }

  // Broadcast events for starting all interfaces!
  cfg->StartInterfaces();

  // Encourage the user!
  printf("\n-- ** OKIE DOKIE, KIDDO! ** --\n");

  // *** SDL IO is now done in main thread- Mac OS X SDL requires it, and on Linux it's one less thread
  SDLIO::run_sdl_thread(sdlio);

  // Old method
#if 0
  // Now just wait.. the threads will take care of everything 
  while (sdlio->IsActive()) {
    usleep(100000);
  };
#endif
  
  // Cleanup
  if (vid != 0)
    vid->close();
  sdlio->close();
  midi->close();
  audio->close();
  if (vid != 0)
    delete vid;
  delete sdlio;
  delete midi;
  delete audio;
  delete iset;
  delete abufs;
  delete[] snaps;

#if USE_FLUIDSYNTH
  delete fluidp;
#endif

  delete[] browsers;

  printf("MAIN: end stage 1\n");

  //sleep(1);

  // Manually reset audio memory to its original state-
  // not preallocated!
  getAMPEAKS()->SetupPreallocated(0,Preallocated::PREALLOC_BASE_INSTANCE);
  getAMAVGS()->SetupPreallocated(0,Preallocated::PREALLOC_BASE_INSTANCE);
  audiomem->SetupPreallocated(0,Preallocated::PREALLOC_BASE_INSTANCE);

  // And main classes..
  delete tmap;
  printf(" 1\n");
  delete loopmgr;
  printf(" 2\n");
  delete rp; 
  printf(" 3\n");
  delete bmg;
  printf(" 4\n");

  printf("MAIN: end stage 2\n");

  //::delete audiomem;
  delete[] scope;

  printf("MAIN: end stage 3\n");

  // Delete preallocated type managers
  delete pre_audioblock;
  delete pre_extrachannel;
  delete pre_timemarker;

  printf("MAIN: end stage 4\n");
  //sleep(2);

  delete cfg;
  printf(" 1\n");
  //sleep(2);
  delete emg;
  //sleep(2);
  printf(" 2\n");
  delete mmg;

  SDL_Quit();
  
  SRMWRingBuffer_Writers::CloseAll();

  printf("MAIN: end\n");

  return 0;
}

BED_MarkerPoints *Fweelin::getAMPEAKSPULSE() { 
  AudioBlock *peaks = getAMPEAKS();
  if (peaks != 0)
    return dynamic_cast<BED_MarkerPoints *>
      (getAMPEAKS()->GetExtendedData(T_BED_MarkerPoints));
  else
    return 0;
};

AudioBlock *Fweelin::getAMPEAKS() { 
  return 
    dynamic_cast<PeaksAvgsManager *>(bmg->GetBlockManager(audiomem,
                                                          T_MC_PeaksAvgs))->
    GetPeaks();
};

AudioBlock *Fweelin::getAMAVGS() { 
  return 
    dynamic_cast<PeaksAvgsManager *>(bmg->GetBlockManager(audiomem,
                                                          T_MC_PeaksAvgs))->
    GetAvgs();
  };

AudioBlockIterator *Fweelin::getAMPEAKSI() { 
  return
    dynamic_cast<PeaksAvgsManager *>(bmg->GetBlockManager(audiomem,
                                                          T_MC_PeaksAvgs))->
    GetPeaksI();
};

AudioBlockIterator *Fweelin::getAMAVGSI() { 
  return
    dynamic_cast<PeaksAvgsManager *>(bmg->GetBlockManager(audiomem,
                                                          T_MC_PeaksAvgs))->
    GetAvgsI();
};

AudioBlockIterator *Fweelin::getAUDIOMEMI() {
  return amrec->GetIterator();
};

Browser *Fweelin::GetBrowserFromConfig(BrowserItemType b) {
  FloDisplay *cur = cfg->displays;
  while (cur != 0) {
    if (cur->GetFloDisplayType() == FD_Browser &&
        ((Browser *) cur)->GetType() == b)
      return (Browser *) cur;
    cur = cur->next;
  }
  return 0;
};

void Fweelin::ToggleDiskOutput()
{
  if (fs->GetStatus() == FileStreamer::STATUS_STOPPED) {
    // Create appropriate filename for output
    char tmp[FWEELIN_OUTNAME_LEN];
    char go = 1;
    do {
      snprintf(tmp,FWEELIN_OUTNAME_LEN,"%s/%s%d%s",
               cfg->GetLibraryPath(),FWEELIN_OUTPUT_STREAM_NAME,writenum,
               getCFG()->GetAudioFileExt(getCFG()->GetStreamOutFormat()));
      struct stat st;
      printf("DISK: Opening '%s' for streaming.\n",tmp);
      if (stat(tmp,&st) == 0) {
        printf("DISK: File exists, trying another.\n");
        writenum++;
      } else {
        // Also check for timing data file- don't overwrite that
        snprintf(timingname,FWEELIN_OUTNAME_LEN,"%s/%s%d%s",
                 cfg->GetLibraryPath(),FWEELIN_OUTPUT_STREAM_NAME,
                 writenum,FWEELIN_OUTPUT_TIMING_EXT);
        if (stat(timingname,&st) == 0) {
          printf("DISK: Timing file exists, trying another.\n");
          writenum++;
        } else
          go = 0;
      }
    } while (go);

    // Compose filename & start writing
    strcpy(streamoutname,tmp);
    snprintf(timingname,FWEELIN_OUTNAME_LEN,"%s/%s%d%s",
             cfg->GetLibraryPath(),FWEELIN_OUTPUT_STREAM_NAME,
             writenum,FWEELIN_OUTPUT_TIMING_EXT);
    fs->StartWriting(streamoutname,timingname,getCFG()->GetStreamOutFormat());
  } else {
    // Stop disk output
    fs->StopWriting();
    strcpy(streamoutname,"");
    strcpy(timingname,"");

    // Advance to next logical filename
    writenum++;
  }
};

int Fweelin::setup()
{
  char tmp[255];

  // Keep all memory inline
  mlockall(MCL_CURRENT | MCL_FUTURE);

  SRMWRingBuffer_Writers::InitAll();
  
  // Initialize vars
  for (int i = 0; i < NUM_LOOP_SELECTION_SETS; i++)
    loopsel[i] = 0;

#ifndef __MACOSX__
  if (!XInitThreads()) {
    printf("MAIN: ERROR: FreeWheeling requires threaded Xlib support\n");
    return 0;
  }
#else  
  FweelinMac::LinkFweelin(this);
#endif
  
  /* Initialize SDL- this happens here because it is common to video, keys &
     config */ 
  // SDL_INIT_NOPARACHUTE
  /* (SDL_INIT_JOYSTICK | SDL_INIT_EVENTTHREAD) < 0) { */
  if ( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0 ) {
    printf("MAIN: ERROR: Can't initialize SDL: %s\n",SDL_GetError());
    return 0;
  }
  atexit(SDL_Quit);

  // Memory manager
  mmg = new MemoryManager();

  // Load configuration from .rc file
  cfg = new FloConfig(this);

  // Create system variables so that config will have them first!
  UserVariable *tmpv;
  tmpv = cfg->AddEmptyVariable("BROWSE_loop");
  tmpv->type = T_int;
  *tmpv = (int) B_Loop;
  tmpv = cfg->AddEmptyVariable("BROWSE_scene");
  tmpv->type = T_int;
  *tmpv = (int) B_Scene;
  tmpv = cfg->AddEmptyVariable("BROWSE_loop_tray");
  tmpv->type = T_int;
  *tmpv = (int) B_Loop_Tray;
  tmpv = cfg->AddEmptyVariable("BROWSE_scene_tray");
  tmpv->type = T_int;
  *tmpv = (int) B_Scene_Tray;
  tmpv = cfg->AddEmptyVariable("BROWSE_patch");
  tmpv->type = T_int;
  *tmpv = (int) B_Patch;
  cfg->AddEmptyVariable("SYSTEM_num_midi_outs");
  cfg->AddEmptyVariable("SYSTEM_midi_transpose");
  cfg->AddEmptyVariable("SYSTEM_master_in_volume");
  cfg->AddEmptyVariable("SYSTEM_master_out_volume");
  cfg->AddEmptyVariable("SYSTEM_cur_pitchbend");
  cfg->AddEmptyVariable("SYSTEM_bender_tune");
  cfg->AddEmptyVariable("SYSTEM_cur_limiter_gain");
  cfg->AddEmptyVariable("SYSTEM_audio_cpu_load");
  cfg->AddEmptyVariable("SYSTEM_sync_active");
  cfg->AddEmptyVariable("SYSTEM_sync_transmit");
  cfg->AddEmptyVariable("SYSTEM_midisync_transmit");
#if USE_FLUIDSYNTH
  cfg->AddEmptyVariable("SYSTEM_fluidsynth_enabled");
#endif
  cfg->AddEmptyVariable("SYSTEM_num_help_pages");
  cfg->AddEmptyVariable("SYSTEM_num_loops_in_map");
  cfg->AddEmptyVariable("SYSTEM_num_recording_loops_in_map");
  cfg->AddEmptyVariable("SYSTEM_num_patchbanks");
  cfg->AddEmptyVariable("SYSTEM_cur_patchbank_tag");
  cfg->AddEmptyVariable("SYSTEM_num_switchable_interfaces");
  cfg->AddEmptyVariable("SYSTEM_snapshot_page_firstidx");
  for (int i = 0; i < LAST_REC_COUNT; i++) {
    sprintf(tmp,"SYSTEM_loopid_lastrecord_%d",i);
    cfg->AddEmptyVariable(tmp);
  }

  // Now parse and setup config
  cfg->Parse();

  // Event manager
  emg = new EventManager();

  vid = new VideoIO(this);
  if (vid->activate()) {
    printf("MAIN: ERROR: Can't start video handler!\n");
    return 1;
  }
  while (!vid->IsActive())
    usleep(100000);

  abufs = new AudioBuffers(this);
  iset = new InputSettings(this,abufs->numins);
  audio = new AudioIO(this);
  if (audio->open()) {
    printf("MAIN: ERROR: Can't start system level audio!\n");
    return 1;
  }  
  fragmentsize = audio->getbufsz();
  printf("MAIN: Core block size: %d\n",fragmentsize);

  // Linkup to browsers
  browsers = new Browser *[(int) B_Last];
  memset(browsers,0,sizeof(Browser *) * (int) B_Last);

  // Setup patch browser, if defined in config
  {
    Browser *br = GetBrowserFromConfig(B_Patch);
    if (br != 0) {
      browsers[B_Patch] = br;
      br->Setup(this,this); // We handle callbacks ourselves for patch browser
    }
  }

  // FluidSynth
#if USE_FLUIDSYNTH
  // Create synth
  printf("MAIN: Creating integrated FluidSynth.\n");
  fluidp = new FluidSynthProcessor(this,cfg->GetFluidStereo());
  
  // Setup patch names
  fluidp->SetupPatches();
#endif

  // Setup sample buffer for visual scope
  scope = new sample_t[fragmentsize];
  scope_len = fragmentsize;

  // Block manager
  bmg = new BlockManager(this);

  // Preallocated type managers
  pre_audioblock = new PreallocatedType(mmg, ::new AudioBlock(),
                                        sizeof(AudioBlock),
                                        FloConfig::
                                        NUM_PREALLOCATED_AUDIO_BLOCKS);

  if (cfg->IsStereoMaster()) 
    // Only preallocate for stereo blocks if we are running in stereo
    pre_extrachannel = new PreallocatedType(mmg, ::new BED_ExtraChannel(),
                                            sizeof(BED_ExtraChannel),
                                            FloConfig::
                                            NUM_PREALLOCATED_AUDIO_BLOCKS);
  else 
    pre_extrachannel = 0;
  pre_timemarker = new PreallocatedType(mmg,::new TimeMarker(),
                                        sizeof(TimeMarker),
                                        FloConfig::
                                        NUM_PREALLOCATED_TIME_MARKERS);

  rp = new RootProcessor(this,iset);
  // Add monitor mix
  float *inputvol = &(rp->inputvol); // Where to get input vol from
  rp->AddChild(new PassthroughProcessor(this,iset,inputvol),
               ProcessorItem::TYPE_GLOBAL);
  // Add disk writer
  rp->AddChild(fs = new FileStreamer(this),
               ProcessorItem::TYPE_FINAL);
  writenum = 1;
  strcpy(streamoutname,"");
  curscene = 0;
#if 0
  strcpy(scenedispname,"");
  strcpy(scenefilename,"");
#endif
  strcpy(timingname,"");

  // Fixed audio memory
  nframes_t memlen = (nframes_t) (audio->get_srate() * 
                                  cfg->AUDIO_MEMORY_LEN),
    scopelen = cfg->GetScopeSampleLen(),
    chunksize = memlen/scopelen;
  // Note here we bypass using Preallocated RTNew because we want
  // a single block of our own size, not many preallocated blocks
  // chained together..
  audiomem = ::new AudioBlock(memlen);
  if (audiomem == 0) {
    printf("CORE: ERROR: Can't create audio memory!\n");
    exit(1);
  }
  audiomem->Zero();
  // If we are running in stereo, create a custom right channel to match
  // our left channel audio memory
  if (cfg->IsStereoMaster()) {
    BED_ExtraChannel *audiomem_r = ::new BED_ExtraChannel(memlen);
    if (audiomem_r == 0) {
      printf("CORE: ERROR: Can't create audio memory (right channel)!\n");
      exit(1);
    }
    
    audiomem->AddExtendedData(audiomem_r);
  }

  // So we have to set a pointer manually to the manager..
  // Because some functions depend on using audiomem as a basis
  // to access RTNew
  audiomem->SetupPreallocated(pre_audioblock,
                              Preallocated::PREALLOC_BASE_INSTANCE);

  // Begin recording into audio memory (use mono/stereo memory as appropriate)
  amrec = new RecordProcessor(this,iset,inputvol,audiomem,
                              cfg->IsStereoMaster());
  if (amrec == 0) {
    printf("CORE: ERROR: Can't create core RecordProcessor!\n");
    exit(1);
  }
  rp->AddChild(amrec,ProcessorItem::TYPE_HIPRIORITY);
  // Compute running peaks and averages from audio mem (for scope)
  AudioBlock *peaks = ::new AudioBlock(scopelen),
    *avgs = ::new AudioBlock(scopelen);
  if (peaks == 0 || avgs == 0) {
    printf("CORE: ERROR: Can't create peaks/averages memory!\n");
    exit(1);
  }
  peaks->Zero();
  avgs->Zero();
  // **BUG-- small leak-- the above two are never deleted
  peaks->SetupPreallocated(pre_audioblock,
                           Preallocated::PREALLOC_BASE_INSTANCE);
  avgs->SetupPreallocated(pre_audioblock,
                          Preallocated::PREALLOC_BASE_INSTANCE);
  audiomem->AddExtendedData(new BED_PeaksAvgs(peaks,avgs,chunksize));
  bmg->PeakAvgOn(audiomem,amrec->GetIterator());

  int nt = cfg->GetNumTriggers();
  tmap = new TriggerMap(this,nt);
  loopmgr = new LoopManager(this);

  // Setup loop & scene browsers & trays, if defined in config
  {
    Browser *br = GetBrowserFromConfig(B_Loop);
    if (br != 0) {
      browsers[B_Loop] = br;
      br->Setup(this,loopmgr);
    }
    loopmgr->SetupLoopBrowser();

    br = GetBrowserFromConfig(B_Scene);
    if (br != 0) {
      browsers[B_Scene] = br;
      br->Setup(this,loopmgr);
    }
    loopmgr->SetupSceneBrowser();

    br = GetBrowserFromConfig(B_Loop_Tray);
    if (br != 0) {
      browsers[B_Loop_Tray] = br;
      br->Setup(this,loopmgr);
    }
  }

  // Create snapshots
  snaps = new Snapshot[cfg->GetMaxSnapshots()];

  // Input methods 
  sdlio = new SDLIO(this);
  midi = new MidiIO(this);

  if (sdlio->activate()) {
    printf("(start) cant start keyboard handler\n");
    return 1;
  }
  if (midi->activate()) {
    printf("(start) cant start midi\n");
    return 1;
  }
  
  // Linkup system variables
  cfg->LinkSystemVariable("SYSTEM_num_midi_outs",T_int,
                          (char *) &(cfg->midiouts));
  cfg->LinkSystemVariable("SYSTEM_midi_transpose",T_int,
                          (char *) &(cfg->transpose));
  cfg->LinkSystemVariable("SYSTEM_master_in_volume",T_float,
                          (char *) &(rp->inputvol));
  cfg->LinkSystemVariable("SYSTEM_master_out_volume",T_float,
                          (char *) &(rp->outputvol));
  cfg->LinkSystemVariable("SYSTEM_cur_pitchbend",T_int,
                          (char *) &(midi->curbender));
  cfg->LinkSystemVariable("SYSTEM_bender_tune",T_int,
                          (char *) &(midi->bendertune));
  cfg->LinkSystemVariable("SYSTEM_cur_limiter_gain",T_float,
                          (char *) &(rp->curlimitvol));
  cfg->LinkSystemVariable("SYSTEM_audio_cpu_load",T_float,
                          (char *) &(audio->cpuload));
  cfg->LinkSystemVariable("SYSTEM_sync_active",T_char,
                          (char *) &(audio->sync_active));
  cfg->LinkSystemVariable("SYSTEM_sync_transmit",T_char,
                          (char *) &(audio->timebase_master));
  cfg->LinkSystemVariable("SYSTEM_midisync_transmit",T_char,
                          (char *) &(midi->midisyncxmit));
#if USE_FLUIDSYNTH
  cfg->LinkSystemVariable("SYSTEM_fluidsynth_enabled",T_char,
                          (char *) &(fluidp->enable));
#endif
  cfg->LinkSystemVariable("SYSTEM_num_help_pages",T_int,
                          (char *) &(vid->numhelppages));
  cfg->LinkSystemVariable("SYSTEM_num_loops_in_map",T_int,
                          (char *) &(loopmgr->numloops));
  cfg->LinkSystemVariable("SYSTEM_num_recording_loops_in_map",T_int,
                          (char *) &(loopmgr->numrecordingloops));
  cfg->LinkSystemVariable("SYSTEM_num_recording_loops_in_map",T_int,
                          (char *) &(loopmgr->numrecordingloops));
  if (browsers[B_Patch] != 0) {
    cfg->LinkSystemVariable("SYSTEM_num_patchbanks",T_int,
                          (char *) &(((PatchBrowser *) browsers[B_Patch])->
                                     num_pb));
    cfg->LinkSystemVariable("SYSTEM_cur_patchbank_tag",T_int,
                          (char *) &(((PatchBrowser *) browsers[B_Patch])->
                                     pb_cur_tag));
  }
  cfg->LinkSystemVariable("SYSTEM_num_switchable_interfaces",T_int,
                          (char *) &(cfg->numinterfaces));
  for (int i = 0; i < LAST_REC_COUNT; i++) {
    sprintf(tmp,"SYSTEM_loopid_lastrecord_%d",i);
    cfg->LinkSystemVariable(tmp,T_int,
                            (char *) &(loopmgr->lastrecidx[i]));
  }
  for (int i = 0; i < iset->numins; i++) {
    snprintf(tmp,255,"SYSTEM_in_%d_volume",i+1);
    cfg->LinkSystemVariable(tmp,T_float,
                            (char *) &(iset->invols[i]));
    snprintf(tmp,255,"SYSTEM_in_%d_peak",i+1);
    cfg->LinkSystemVariable(tmp,T_float,
                            (char *) &(iset->inpeak[i]));
    snprintf(tmp,255,"SYSTEM_in_%d_record",i+1);
    cfg->LinkSystemVariable(tmp,T_char,
                            (char *) &(iset->selins[i]));
  }
  {
    FloDisplaySnapshots *sn = 
      (FloDisplaySnapshots *) cfg->GetDisplayByType(FD_Snapshots);
    if (sn != 0)
      cfg->LinkSystemVariable("SYSTEM_snapshot_page_firstidx",T_int,
                              (char *) &(sn->firstidx));
  }

  // Finally, final Config start
  cfg->Start();

  // Now start signal processing
  if (audio->activate(rp)) {
    printf("MAIN: Error with signal processing start!\n");
    return 1;
  }

  return 0;
}

void Fweelin::ItemSelected(BrowserItem *i) { 
  if (i->GetType() != B_Patch) 
    printf("CORE: ERROR- Patch Browser contains items of invalid type!\n");
  else {
    PatchBrowser *br = (PatchBrowser *) getBROWSER(B_Patch);

    if (br != 0) {
      PatchBank *pb = br->GetCurPatchBank();
      if (pb->port == 0) {
        // We are selecting in a Fluidsynth bank-- send patch change
#if USE_FLUIDSYNTH
        getFLUIDP()->SendPatchChange((PatchItem *) i);
#else
        printf("CORE: ERROR: Can't change FluidSynth patches- no FluidSynth "
               "support!\n");
#endif
      } else {
        // Check if change messages to be sent?
        if (!pb->suppresschg) {
          // Tell MIDI to send out bank/program change(s) for new patch
          getMIDI()->SendBankProgramChange((PatchItem *) i);
        }
      }
    }
  }
};