aboutsummaryrefslogtreecommitdiff
path: root/src/lib/hd24fs.cpp
blob: 5c6b3fced49920eecd4e52dbc1f2c4eff4587935 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
#define ALLOC_SECTORS_PER_SONG	5
#define SONG_SECTORS_PER_SONG	2
#define TOTAL_SECTORS_PER_SONG	(ALLOC_SECTORS_PER_SONG+SONG_SECTORS_PER_SONG)
#ifdef DARWIN
#define creat64 creat
#endif
#define HD24FSDEBUG 0	   /* generic hd24fs debugging */
#define HD24FSDEBUG_QUICKFORMAT 0  /* debugging for calculation of # of free clusters */
#define HD24FSDEBUG_WRITE 0 /* output debugging messages on disk writes */
#define HD24FSDEBUG_BITSET 0 /* output debugging messages on disk writes */
#define HD24FSDEBUG_COMMIT 0 /* output debugging messages on disk writes */
#define HD24FSDEBUG_DEVSCAN 0 /* output debugging messages for device scan */
#include "hd24fs.h"
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef WINDOWS
#include <unistd.h>
#endif
#define RESULT_SUCCESS 0
#define RESULT_FAIL 1
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <math.h>
#include "convertlib.h"
#include "memutils.h"

#include <hd24devicenamegenerator.h>
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#define FILE_OFFSET_BITS 64
#define LARGE_FILES
#define LARGEFILE64_SOURCE
#define SECTORSIZE 512
#ifdef DARWIN
#define open64 open
#define lseek64 lseek
#define pread64 pread
#define pwrite64 pwrite
#endif
#define FSINFO_VERSION_MAJOR 		0x8
#define FSINFO_VERSION_MINOR 		0x9
#define FSINFO_BLOCKSIZE_IN_SECTORS	0x10
#define FSINFO_AUDIOBLOCKS_PER_CLUSTER	0x14
#define FSINFO_STARTSECTOR_DRIVEUSAGE	0x38
#define FSINFO_NUMSECTORS_DRIVEUSAGE	0x3c
#define FSINFO_FREE_CLUSTERS_ON_DISK	0x44
#define FSINFO_FIRST_PROJECT_SECTOR	0x48
#define FSINFO_SECTORS_PER_PROJECT	0x4C
#define FSINFO_MAXPROJECTS		0x50
#define FSINFO_MAXSONGSPERPROJECT	0x54
#define FSINFO_FIRST_SONG_SECTOR	0x58
#define FSINFO_SECTORS_IN_SONGENTRY	0x5C
#define FSINFO_SECTORS_IN_SONGALLOC	0x60
#define FSINFO_SECTORS_PER_SONG		0x64
#define FSINFO_CURRENT_SONGS_ON_DISK	0x68
#define FSINFO_ALLOCATABLE_SECTORCOUNT  0x80
#define FSINFO_LAST_SECTOR              0x84
#define FSINFO_DATAAREA 		0x7c

#define DRIVEINFO_VOLUME 	0x1b8
#define DRIVEINFO_VOLUME_8 	0x00
#define DRIVEINFO_PROJECTCOUNT	0x0c
#define DRIVEINFO_LASTPROJ	0x10
#define DRIVEINFO_LASTPROJECT	0x10
#define DRIVEINFO_PROJECTLIST	0x20

#include "hd24project.cpp"
#include "hd24song.cpp"
#if defined(LINUX) || defined(DARWIN)
const int hd24fs::MODE_RDONLY=O_RDONLY;
const int hd24fs::MODE_RDWR=O_RDWR;
#endif
#ifdef WINDOWS
#include <shellapi.h>
const int hd24fs::MODE_RDONLY=GENERIC_READ;
const int hd24fs::MODE_RDWR=GENERIC_READ|GENERIC_WRITE;
#define popen _popen
#define pclose _pclose
#endif

const int hd24fs::TRANSPORTSTATUS_STOP  =0;
const int hd24fs::TRANSPORTSTATUS_REC   =1;
const int hd24fs::TRANSPORTSTATUS_PLAY  =2;

void dumpsector(const char* buffer)
{
	for (int i=0;i<512;i+=16) {
		string* dummy=Convert::int32tohex(i);
	       	cout << *dummy	<< "  ";
		delete dummy; dummy=NULL;
		for (int j=0;j<16;j++) {
			string* dummy= Convert::byte2hex(buffer[i+j]);
			cout << *dummy;
			if (j==7) {
				cout << "-" ;
			} else {
				cout << " " ;
			}
			delete dummy; dummy=NULL;
		}
		cout << " ";
		for (int j=0;j<16;j++) {
			cout << Convert::safebyte(buffer[i+j]);
		}
		cout << "" << endl;
	}
}

__uint32 hd24fs::songentry2sector(__uint32 songentry)
{
	// Given the possibility to store 99*99 songs,
	// converts the song number (0..99*99-1) to
	// the sector where the info of that song starts.
	// TODO: answer is FSINFO_FIRST_SONG_SECTOR+(FSINFO_SECTORS_PER_SONG*songentry)
	// returns 0 when entry number is not legal.
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// info needed for the calculation is missing.
		return 0;
	}
	__uint32 firstsongsec=Convert::getint32(sector_boot,FSINFO_FIRST_SONG_SECTOR);
	__uint32 secspersong=Convert::getint32(sector_boot,FSINFO_SECTORS_PER_SONG);
	if (songentry<(99*99)) {
		__uint32 secnum=(firstsongsec+(songentry*secspersong));
		return secnum;
	}
	return 0; // entry number is not legal.
}

__uint32 hd24fs::songsondisk()
{
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// info needed for the calculation is missing.
		return 0;
	}
	return Convert::getint32(sector_boot,FSINFO_CURRENT_SONGS_ON_DISK);
}

void hd24fs::songsondisk(__uint32 songcount)
{
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// info needed for the calculation is missing.
		return; //cannot update.
	}
	Convert::setint32(sector_boot,FSINFO_CURRENT_SONGS_ON_DISK,songcount);	
}

__uint32 hd24fs::songsector2entry(__uint32 songsector)
{
	// given the sector where a song entry starts,
	// returns the entry number of that song.
	// Entry number typically ranges from 0
	// to (99*99)-1.
	// A value 0xffffffff is returned when the 
	// sector number is not valid. 
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// info needed for the calculation is missing.
		return 0xFFFFFFFF; // sector number is not valid.
	}
	__uint32 firstsongsec=Convert::getint32(sector_boot,FSINFO_FIRST_SONG_SECTOR);
	__uint32 secspersong=Convert::getint32(sector_boot,FSINFO_SECTORS_PER_SONG);
	__uint32 offset=songsector-firstsongsec;
	if ((offset%secspersong) !=0) {
		return 0xFFFFFFFF; // sector number is not valid.
	}
	__uint32 resultentry=(offset/secspersong);
	if (resultentry>=(99*99)) return 0xFFFFFFFF;
	return resultentry;
}

__uint32 hd24fs::cluster2sector(__uint32 clusternum)
{
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// unknown cluster size.
		return 0;
	}
	return Convert::getint32(sector_boot,FSINFO_DATAAREA) /* first audio sector */
	+(
		Convert::getint32(sector_boot,FSINFO_BLOCKSIZE_IN_SECTORS)
		* Convert::getint32(sector_boot,FSINFO_AUDIOBLOCKS_PER_CLUSTER)
		* clusternum
	);
}

__uint32 hd24fs::sector2cluster(__uint32 sectornum)
{
	getsector_bootinfo();
	if (sector_boot==NULL) {
		// unknown cluster size. Return 'undefined' cluster number.
		return CLUSTER_UNDEFINED;
	}
	__uint32 dataarea=Convert::getint32(sector_boot,FSINFO_DATAAREA);
	
	if (sectornum<dataarea) {
		// A cluster number of a sector outside the data area was requested.
		return CLUSTER_UNDEFINED;
	}

	__uint32 unoffsetsector=sectornum-dataarea;
	__uint32 sectorspercluster=
		Convert::getint32(sector_boot,FSINFO_BLOCKSIZE_IN_SECTORS)
		* Convert::getint32(sector_boot,FSINFO_AUDIOBLOCKS_PER_CLUSTER);
	__uint32 firstsectorofcluster=unoffsetsector-(unoffsetsector%sectorspercluster);
	__uint32 cluster=firstsectorofcluster/sectorspercluster;
	return cluster;
}

__uint32 hd24fs::getnextfreesector(__uint32 cluster)
{
	if (cluster==CLUSTER_UNDEFINED) {
		__uint32 result=getnextfreesectorword();
#if (HD24FSDEBUG==1)
		cout << result << endl;
#endif
		return result;
	}
	if (isfreecluster(cluster+1,&sectors_driveusage[0])) 
	{
		return cluster2sector(cluster+1);
	}	
	return getnextfreesectorword();
}

__uint32 hd24fs::getnextfreesectorword()
{
	__uint32 cluster=getnextfreeclusterword();
	if (cluster==CLUSTER_UNDEFINED) {
		return 0;
	}
	return cluster2sector(cluster);
}

__uint32 hd24fs::getnextfreeclusterword()
{
	getsectors_driveusage();
	__uint32 driveusagecount=driveusagesectorcount();
	__uint32 driveusagewords=driveusagecount*(512/4);

	// For performance reasons, we start searching
	// at last result+1 (this will typically result
	// in an immediate hit).
	// Wrap around to cluster 0 if nothing found.

#if (HD24FSDEBUG==1)
	cout << " start search at " << nextfreeclusterword << endl;
#endif
	__uint32 i=nextfreeclusterword;
	__uint32 initsec=i;
		
	bool foundfree=false;
	while (i<driveusagewords) {
		if (Convert::getint32(&sectors_driveusage[0],i*4)==0) {
			foundfree=true;
			break;
		}
		i++;
	}
	if (!foundfree) {
		if (initsec==0) {
			// we didnt find anything although
			// we started searching at cluster 0.
			return CLUSTER_UNDEFINED;
		} else {
			// we didnt find anything but started
			// searching at a cluster>0. Wrap around.
			nextfreeclusterword=0;
			return getnextfreeclusterword();
		}
	}
	// we found a (set of 32) free cluster(s).
	nextfreeclusterword=i;
	return (i*32);
}

unsigned long hd24fs::getlastsectornum() 
{
#if (HD24FSDEBUG==1)
	cout <<"hd24fs::getlastsectornum()" << endl;
#endif
	// cache result.
	if (gotlastsectornum==false) {
		foundlastsectornum=getlastsectornum(devhd24);
		gotlastsectornum=true;
	}
	return foundlastsectornum;
}

void hd24fs::setwavefixmode(int mode) 
{
	wavefixmode=mode;
}

void hd24fs::setmaintenancemode(int mode) 
{
	maintenancemode=mode;
}

int hd24fs::getmaintenancemode() 
{
	return maintenancemode;
}

string* hd24fs::getdevicename() {

	return this->devicename;
}

void hd24fs::setdevicename(const char* orig,string* devname)
{
	if (this->devicename!=NULL) {
		delete this->devicename;
		this->devicename=NULL;
	}
	this->devicename=new string(devname->c_str());
}

unsigned long hd24fs::getlastsectornum(FSHANDLE handle) 
{
#if (HD24FSDEBUG==1)
	cout <<"hd24fs::getlastsectornum(FSHANDLE handle)" << endl;
#endif
#if defined(LINUX) || defined(DARWIN)
	__uint64 curroff=lseek64(handle,0,SEEK_CUR);
	__uint64 sectors=(lseek64(handle,0,SEEK_END)+1)>>9;
	lseek64(handle,curroff,SEEK_SET);
	return sectors-1;
#endif
	/* unfortunately, apart from other functions being needed
	 * to read 64 bit files, the elegant solution above won't
	 * work on Windows, because it is not possible to
	 * request the file size of a device.
	 */
	
#ifdef WINDOWS
	unsigned char buffer[2048];
	LARGE_INTEGER lizero;
	lizero.QuadPart=0;
	LARGE_INTEGER saveoff;
	LARGE_INTEGER filelen;
	filelen.QuadPart=0;
	SetFilePointerEx(handle,lizero,&saveoff,FILE_CURRENT); // save offset
	/* If things would work properly, the following would
	 * not only work for regular files, but also for devices.
	 * Perhaps the next version of Windows has proper hardware
	 * abstraction and this will magically start working.
	 */
	if (0!=SetFilePointerEx(handle,lizero,&filelen,FILE_END)) {
		SetFilePointerEx(handle,saveoff,NULL,FILE_BEGIN); // restore offset
		return ((filelen.QuadPart)/512);
	}
	SetFilePointerEx(handle,saveoff,NULL,FILE_BEGIN); // restore offset
#if (HD24FSDEBUG==1)
	cout << "fileptr method failed" << endl;
#endif
	/* The proper way to do things has failed (probably because
	 * we are dealing with a device file instead of with a 
	 * regular one.
	 */

	/* TODO: Before trying a raw sectornum scan, 
           we can still check if we're dealing with a valid
           superblock, not using a headerfile and checking if
           the last sector as indicated by the superblock points
           to a copy of that superblock. This won't work on a raw
           drive, of course, but will provide a reasonably safe
           workaround for valid HD24 drives. */

	/* The workaround has also failed, so we need to perform
           raw drive size detection. Windows does not have a reliable
           way to get the real LBA sector count, so we need to perform
           the following semi-smart trick (if you have a better idea that
	   works on all windows versions and all drive types,
	   I'd be thrilled to know!)

	   - First, iterate reading sector numbers until it fails.
	     To keep speed acceptable, multiply sector number by 2
	     each time.
	   - After failed read, do a binary search between the
	     failed read sector number and the sector number of
	     the last successful read.
	   - As the drive MUST be aware of its own size, this will
             give the real sector count of the drive.
	 */
	lizero.QuadPart=0;
	saveoff.QuadPart=0;

	LARGE_INTEGER maxbytes;
	maxbytes.QuadPart=0;
	SetFilePointerEx(handle,lizero,&saveoff,FILE_CURRENT); // save offset

	long bytesread=1;
	unsigned long trysector=1;
	unsigned long oldtrysector=1;
	int drivetoosmall=1;
	bytesread=readsectors(handle,trysector,buffer,1); // raw/audio read (no fstfix needed)
	unsigned long lastok=0;
	unsigned long firstfail=0;
	//int dummy;
	/* This loop doubles the sector number. Actually stays at 2^n-1,
	 * this will likely perform better than 2^n because chances are
	 * greater that it stays below disk boundaries, preventing slow
	 * timeouts.
	 */
	while (bytesread>0) 
	{
#if (HD24FSDEBUG==1)
		cout << "trysector=" << trysector << endl;
#endif
//		cin >> dummy;
		drivetoosmall=0;
		oldtrysector=trysector;
		trysector=trysector*2+1; // count will be 1,3,7,15,31,... =(2^n)-1
		if (oldtrysector==trysector) 
		{
			// x*2+1 yields x - this means all
			// bits are turned on and we overflow.
			// So we're at 4 tera limit.
			// 4 terabyte and still nothing found? hmmmm	
			SetFilePointerEx(handle,saveoff,NULL,FILE_BEGIN);
			return 0;
		}
		bytesread=0;
		bytesread=readsectors(handle,trysector,buffer,1); // raw/audio read (no fstfix needed)
#if (HD24FSDEBUG==1)
		cout << "   bytesread=" <<bytesread << endl;
#endif
		if (bytesread>0) {
			lastok=trysector;
		} else {
			firstfail=trysector;
		}
	}
	/* We have the sector number of the last successful read and
	 * of the failed read. Time to do a binary search. */
	unsigned long lowerbound=lastok;
#if (HD24FSDEBUG==1)
	cout << "lastok=" << lastok << endl;
	cout << "firstfaiL=" << firstfail << endl;

#endif
	if (lastok==0) 
	{
		if (firstfail==0)
		{
			return 0;
		}
	}
	unsigned long upperbound=lastok*2;
	unsigned long midpos=0;
	while (lowerbound<=upperbound) 
	{
		//midpos=lowerbound+floor((upperbound-lowerbound)/2);
		midpos=lowerbound+(__uint32)floor((upperbound-lowerbound)/8); 
		// prefer asymmetrical search due to time out when
		// searching past upperbound
//		cout << "try=" << midpos << endl;
		bytesread=readsectors(handle,midpos,buffer,1); // raw/audio read (no fstfix needed)
		if (bytesread>0) {
			lowerbound=midpos+1;
		} else {
			// could not read midpos, 
			// so upperbound is before that.
			upperbound=midpos-1;
		}	
	}
	if (midpos==lowerbound)
	{
		midpos--;
	}
	/* midpos is now last sector number. counting starts at sector 0
	 * so total number of sectors is one more. */
	midpos++;
	SetFilePointerEx(handle,saveoff,&saveoff,FILE_BEGIN); //restore
	
	__uint64 sectors=midpos;
//	cout << "found " <<sectors << "sectors " <<endl;
	return sectors;
#endif
}

/* The hd24raw class provides sector level access to hd24 disks
 * which is functionality that is shielded off in hd24fs.
 */

__uint32 hd24raw::songsondisk()
{
	return fsys->songsondisk();
}

__uint32 hd24raw::getlastsectornum()
{
	return fsys->getlastsectornum();
}

__uint32 hd24raw::getprojectsectornum(__uint32 x)
{
	return fsys->getprojectsectornum(x);
}

__uint32 hd24raw::quickformat(char* message)
{
	return fsys->quickformat(message);
}

unsigned long hd24raw::getnextfreesector(__uint32 cluster)
{
	return fsys->getnextfreesector(cluster);
}

hd24raw::hd24raw(hd24fs* p_fsys) 
{
	fsys=p_fsys;
}

long hd24raw::readsectors(unsigned long secnum, unsigned char* buffer,int sectors) 
{
	return fsys->readsectors(fsys->devhd24, secnum, buffer,sectors);
}

long hd24raw::writesectors(unsigned long secnum, unsigned char* buffer,int sectors) 
{
	return fsys->writesectors(fsys->devhd24, secnum, buffer,sectors);
};

bool hd24fs::isinvalidhandle(FSHANDLE handle)
{
#ifdef WINDOWS
	if (handle==FSHANDLE_INVALID) {
		return true;
	}
#endif
#if defined(LINUX) || defined(DARWIN)
	if (handle==0) {
		return true;
	}
	if (handle==FSHANDLE_INVALID) {
		return true;
	}
#endif
	return false;
}

bool hd24fs::isexistingdevice(string* devname) 
{
#if defined(LINUX) || defined(DARWIN)
#if (HD24FSDEBUG==1)
cout << "try open device " << devname->c_str() << endl;
#endif
	FSHANDLE handle=open64(devname->c_str(),MODE_RDONLY); //read binary
#endif
#ifdef WINDOWS
	FSHANDLE handle=CreateFile(devname->c_str(),MODE_RDONLY,
	             FILE_SHARE_READ|FILE_SHARE_WRITE,
	             NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
#endif
	if (!isinvalidhandle(handle)) return true;
	return false;	
}

FSHANDLE hd24fs::findhd24device(int mode,string* devname,bool force,bool tryharder) 
{
#if (HD24FSDEBUG_DEVSCAN==1)
	cout << "FSHANDLE hd24fs::findhd24device(" << mode << ", " << *devname << ", force=" << force << ",tryharder=" << tryharder <<")" << endl;
#endif
        unsigned char findhdbuf[1024];
        unsigned char compare1buf[1024];
        unsigned char compare2buf[1024];
#if defined(LINUX)
	FSHANDLE handle=open64(devname->c_str(),mode,0); //read binary
#endif
#if defined(DARWIN)
	FSHANDLE handle=open64(devname->c_str(),mode); //read binary
#endif
#ifdef WINDOWS
#if (HD24FSDEBUG_DEVSCAN==1)
	cout << "Mode=" << mode << endl;
#endif
	FSHANDLE handle=CreateFile(devname->c_str(),mode,
		FILE_SHARE_READ|FILE_SHARE_WRITE,
		NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
#endif

	if (isinvalidhandle(handle)) {
		if (mode==MODE_RDWR) 
		{
			// attempt fallback to read-only mode
			// (for CDROM/DVD devices etc)
			mode=MODE_RDONLY;
#if defined(LINUX) || defined(DARWIN)
			handle=open64(devname->c_str(),mode); //read binary
#endif
#ifdef WINDOWS
#if (HD24FSDEBUG==1)
//	cout << "Mode=" << mode << endl;
#endif
			handle=CreateFile(devname->c_str(),mode,
			FILE_SHARE_READ|FILE_SHARE_WRITE,
			NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
#endif

		}


	}

	if (isinvalidhandle(handle)) {
		return handle;
	}

	// can open device.
	__uint32 sectornum=0;
	if (tryharder) {
		sectornum=getlastsectornum(handle);
	}

        readsector_noheader(handle,sectornum,findhdbuf); // fstfix follows
	fstfix(findhdbuf,512);
        string* fstype=Convert::readstring(findhdbuf,0,8);
	bool isadat=false;
	
        if (*fstype=="ADAT FST") {
		/* Okay, but if we are 'trying harder' we can run into
 		   a false positive for old HD24 drives that are now in
		   use as OS drive. So we'll demand that the second and
                   secondlast sector are equal.
		*/
		if (tryharder) 
		{
	                readsector_noheader(handle,sectornum-1,compare1buf); 
	                readsector_noheader(handle,1,compare2buf); 
			if (memcmp(compare1buf,compare2buf,512)==0) 
			{
				isadat=true;
			}
			else 
			{
				/* Drive may have been an ADAT drive,
				   but no longer is. If it is in fact an 
                                   ADAT drive but corrupted, it is still 
                                   possible to force detection using force 
                                   mode. Give it another chance; do not
                                   enable write prevention for now.
                                */
				isadat=false;
			}
		}
		else 
		{
			isadat=true;
		}
	}
	delete fstype;

	if (isadat) return handle;

	if (force) 
	{
		forcemode=true;
		m_isOpen=true;
		this->writeprotected=true; // TODO: unless expert mode is enabled too. May also be overridden to allow formatting.
		return handle;
	}
        hd24closedevice(handle);
	return FSHANDLE_INVALID;
}

unsigned long hd24fs::hd24devicecount() 
{
	/* Attempt to auto-detect a hd24 disk on all IDE and SCSI devices.
           (this should include USB and firewire) */
        FSHANDLE handle;
	int devcount=0;
#if (HD24FSDEBUG==1)
	cout << "====PERFORMING DEVICE COUNT====" << endl;	
#endif
	hd24devicenamegenerator* dng=new hd24devicenamegenerator();
	dng->imagedir(this->imagedir);
	
	__uint32 totnames=dng->getnumberofnames();
//	cout << totnames << " devices" << endl;		
        for (__uint32 j=0;j<2;j++) 
	{
		// 2 loops: one to try, one to try harder
		// first loop searches strictly valid devices 
		// second loop searches for possibly corrupted devices
		bool tryharder=false;
		if (j==1) {
			tryharder=true;
		}
	        for (__uint32 i=0;i<totnames;i++) 
		{
			string* devname=dng->getdevicename(i);
			handle=findhd24device(MODE_RDONLY,devname,false,tryharder);
#if (HD24FSDEBUG_DEVSCAN==1)
			cout << "try device no " <<i << "with name" << *devname << "...";
#endif
			delete (devname);
			if (!(isinvalidhandle(handle))) 
			{
				devcount++;
	//			cout << "found" << endl;
				hd24closedevice(handle);
			} else {
	//			cout << "nope." << endl;
			}
	        }

		if (devcount>0) {		
			break;
		}
	}
#if (HD24FSDEBUG==1)
	cout << "====END OF DEVICE COUNT, " << devcount << " DEVICES FOUND ====" << endl;	
#endif
	delete (dng);
        return devcount;
}

void hd24fs::setimagedir(const char* newdir)
{
#if (HD24FSDEBUG==1)
if (newdir==NULL)
{
	cout << "hd24fs::setimagedir(NULL)"<< endl;
}
else
{
	cout << "hd24fs::setimagedir("<<newdir<<")"<< endl;
}
#endif
	
	if (this->imagedir!=NULL)
	{
		free ((void*)imagedir);
		this->imagedir=NULL;
	}

	if (newdir!=NULL)
	{
		this->imagedir=(char*)malloc(strlen(newdir)+1);
		if (this->imagedir!=NULL)
		{
			strncpy((char*)imagedir,newdir,strlen(newdir)+1);		
		}
	}
	
	return; //return (const char*)imagedir;
}

FSHANDLE hd24fs::findhd24device(int mode,int base0devnum) 
{
#if (HD24FSDEBUG_DEVSCAN==1)
	cout << "hd24fs::findhd24device(" << mode << "," << base0devnum << ")" << endl;
#endif
	// TODO: Reduce code duplication in this subroutine
	// and hd24devicecount
	/* Attempt to auto-detect a hd24 disk on all known
	   IDE and SCSI devices. (this should include USB 
	   and firewire) */
	int currdev=0;
        FSHANDLE handle;
	hd24devicenamegenerator* dng=new hd24devicenamegenerator();
	dng->imagedir(this->imagedir);
		
	__uint32 totnames=dng->getnumberofnames();		
#if (HD24FSDEBUG==1)
	cout << totnames << " devices" << endl;		
#endif
        for (__uint32 j=0;j<2;j++) 
	{
		// 2 loops: one to try, one to try harder
		// first loop searches strictly valid devices 
		// second loop searches for possibly corrupted devices

		bool tryharder=false;
		if (j==1) {
			tryharder=true;
		}

	        for (__uint32 i=0;i<totnames;i++) 
		{
			string* devname=dng->getdevicename(i);
			handle=findhd24device(mode,devname,false,tryharder);
			
			if (!(isinvalidhandle(handle))) {
				if (currdev==base0devnum) {
					// String "3" indicates origin, i.e.
					// who is setting the device name.
					// Useful for debugging purposes.
	                                setdevicename("3",devname);
					deviceid=i;
					p_mode=mode;
					delete (devname);
					delete (dng);
					return handle;
				}
				hd24closedevice(handle);
				currdev++;
			}
			delete (devname);
		}
	}
	delete (dng);
        return FSHANDLE_INVALID;
}

void hd24fs::hd24closedevice(FSHANDLE handle) {
#if defined(LINUX) || defined(DARWIN)
	close(handle);
#endif
#ifdef WINDOWS
	CloseHandle(handle);
#endif
}

FSHANDLE hd24fs::findhd24device(int mode) 
{
	/* Attempt to auto-detect a hd24 disk on all IDE and SCSI devices.
           (this should include USB and firewire) */
	return findhd24device(mode,0);
}

FSHANDLE hd24fs::findhd24device() 
{
	return findhd24device(MODE_RDONLY);
}

int hd24fs::gettransportstatus()
{
	return this->transportstatus;
}

void hd24fs::settransportstatus(int newstatus)
{
	this->transportstatus=newstatus;
}

int hd24fs::getdeviceid()
{
	return deviceid;
}

void hd24fs::initvars() 
{
	this->deviceid=-1;
	this->writeprotected=false; // by default allow writes.
				    // can be disabled if corrupt 
				    // state is detected.
	this->transportstatus=TRANSPORTSTATUS_STOP;
	this->imagedir=NULL;
	this->nextfreeclusterword=0;
	this->gotlastsectornum=false;
	this->foundlastsectornum=0;
	this->forcemode=false;
	this->headersectors=0;
	sector_boot=NULL;
	sector_diskinfo=NULL;
	sectors_driveusage=NULL;
	sectors_orphan=NULL;
	sectors_songusage=NULL;
	projlist=NULL;
	this->m_isOpen=false;
	this->allinput=false;
	this->autoinput=false;
	this->wavefixmode=false;
	this->formatting=false;
	this->maintenancemode=false;
	this->headermode=false;
	this->devicename=NULL;
	this->highestFSsectorwritten=0;
	// 0x10c76 is last sector of song/project area (without undo buffer)
	return;	
}

hd24fs::hd24fs(const char* imagedir,int mode)
{
	initvars();
	setimagedir(imagedir);
	devicename=new string("");
	devhd24=findhd24device(mode);
	if (!(isinvalidhandle(devhd24))) {
		m_isOpen=true;
		p_mode=mode;
	}
	return;
}

hd24fs::hd24fs(const char* imagedir,int mode,int base0devnum)
{
#if (HD24FSDEBUG==1)
	cout << "hd24fs::hd24fs(" << mode << "," << base0devnum << ")" << endl;
#endif	
	initvars();
	setimagedir(imagedir);
	devicename=new string("");
	devhd24=findhd24device(mode,base0devnum);
	if (!(isinvalidhandle(devhd24))) {
		m_isOpen=true;
		p_mode=mode;
	}
	return;
}

hd24fs::hd24fs(const char* imagedir,int mode,string* devname,bool force)
{
	initvars();
	setimagedir(imagedir);
	devicename=new string(devname->c_str());
	bool tryharder=false;
	devhd24=findhd24device(mode,devname,force,tryharder);
	if (!(isinvalidhandle(devhd24))) {
		m_isOpen=true;
		p_mode=mode;
	}
	return;
}

hd24fs::hd24fs(const char* imagedir)
{
	initvars();
	setimagedir(imagedir);
	devicename=new string("");
	devhd24=findhd24device(MODE_RDONLY);
	if (!(isinvalidhandle(devhd24))) {
		m_isOpen=true;
		p_mode=MODE_RDONLY;
	}
	return;
}

hd24fs::~hd24fs()
{
#if (HD24FSDEBUG==1)
	cout << "Deleting devicename" << endl;
#endif
	if (devicename!=NULL) {
		delete devicename;
		devicename=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Close FS handle" << endl;
#endif
	if (isOpen())
	{
		hd24close();
	}
#if (HD24FSDEBUG==1)
	cout << "Free superblock mem" << endl;
#endif
	if (sector_boot!=NULL)
	{
		memutils::myfree("sectors_boot",sector_boot);
		sector_boot=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free diskinfo mem" << endl;
#endif
	if (sector_diskinfo!=NULL) 
	{
		memutils::myfree("sectors_diskinfo",sector_diskinfo);
		sector_diskinfo=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free drive usage mem" << endl;
#endif
	if (sectors_driveusage!=NULL)
	{
		memutils::myfree("sectors_driveusage",sectors_driveusage);
		sectors_driveusage=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free orphan sectors mem" << endl;
#endif
	if (sectors_orphan!=NULL)
	{
		memutils::myfree("sectors_orphan",sectors_orphan);
		sectors_orphan=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free song usage sectors mem" << endl;
#endif
	if (sectors_songusage!=NULL)
	{
		memutils::myfree("sectors_songusage",sectors_songusage);
		sectors_songusage=NULL;
	};
	// commit?
}

bool hd24fs::isOpen() 
{
	if (this->m_isOpen) 
	{
		return true;
	}
	return false;
}	

void hd24fs::hd24close() 
{
	// TODO: At the point that we start supporting
	// write access, we will need to flush and close
	// the device here.
	
	hd24closedevice(this->devhd24);
}

void hd24fs::fstfix(unsigned char * bootblock,int fixsize) 
{
	if (bootblock==NULL) return;
	if (fixsize<=0) return;
#if (HD24FSDEBUG==1)
	cout << "fstfix("<<bootblock<<","<<fixsize/512 <<"*512)"<< endl;
#endif
        for (int i=0;i<fixsize;i+=4) 
	{
                unsigned char a=bootblock[i];
                unsigned char b=bootblock[i+1];
                unsigned char c=bootblock[i+2];
                unsigned char d=bootblock[i+3];
                bootblock[i]=d;
                bootblock[i+1]=c;
               	bootblock[i+2]=b;
        	bootblock[i+3]=a;
	}
}

void hd24fs::hd24seek(FSHANDLE devhd24,__uint64 seekpos) {
#if defined(LINUX) || defined(DARWIN)
	lseek64(devhd24,seekpos,SEEK_SET);
#endif
#ifdef WINDOWS
//	cout << "setfp to " <<seekpos << endl;
	LARGE_INTEGER li;
	li.HighPart=seekpos>>32;
	li.LowPart=seekpos%((__uint64)1<<32);
//LowPart=seekpos%
//	SetFilePointer(devhd24,seekpos,NULL,FILE_BEGIN);
	SetFilePointerEx(devhd24,li,NULL,FILE_BEGIN);
	// TODO: SetFilePointer vs SetFilePointerEx
	// DWORD SetFilePointer(
	//   HANDLE hFile,
	//     LONG lDistanceToMove,
	//       PLONG lpDistanceToMoveHigh,
	//         DWORD dwMoveMethod
	//         );
	//
	// vs.
	// BOOL SetFilePointerEx(
	//   HANDLE hFile,
	//     LARGE_INTEGER liDistanceToMove,
	//       PLARGE_INTEGER lpNewFilePointer,
	//         DWORD dwMoveMethod
	//         );
	//
#endif
	return;
}

long hd24fs::writesectors(FSHANDLE devhd24,unsigned long sectornum,unsigned char * buffer,int sectors) 
{
	//////
	// this bit keeps track of the highest FS sector written
	// to keep commit times acceptable: commit function will then
	// only backup up to the highest sector used.
	// (this is still suboptimal performance-wise but requires
	// a minimum of memory and administration during writes).
	__uint32 lastsec=sectornum+(sectors-1);
	if (lastsec<=0x10c76)
	{
		// 0x10c76 is last sector of song/project area (without
		// undo buffer). TODO: calculate based on superblock. info.
		if (lastsec>highestFSsectorwritten)
		{
			highestFSsectorwritten=lastsec;
		}
	}
	//////
	
#if (HD24FSDEBUG_WRITE==1)
		cout << "   writesectors sectornum " << sectornum << ", sectorcount=" << sectors << endl;
#endif
	if (this!=NULL)
	{
		if (this->writeprotected)
		{
#if (HD24FSDEBUG_WRITE==1)
			cout << "Write protected- not writing. " << endl;
#endif
			return 0;
		}
	}
	FSHANDLE currdevice=devhd24;

#if (HD24FSDEBUG_WRITE==1)
	cout << "WRITESECTORS sec=" << sectornum << " buf=" << buffer << "#=" << sectors << endl;
#endif
	int WRITESIZE=SECTORSIZE*sectors; // allows searching across sector boundaries
	
//	cout << "headersectors=" << this->headersectors << "this=" <<this << endl;
	if (this!=NULL)
	{
		if ((this->headersectors)!=0)
		{
//		cout << "headermode enabled." << endl;
			// Header mode is active. Only allow writing over header area.
			if (sectornum<this->headersectors) 
			{
//			cout << "Headermode enabled for sector " << sectornum << endl;
			currdevice=hd24header;

			} else {
				// headermode is active yet caller is trying to write over drive
				// data area. We cannot allow this (for safety reasons).
				return 0;
		
//			cout << "Headermode disabled for sector " << sectornum << endl;
			}
		} else {
//			cout << "Headermode disabled. " << sectornum << endl;
		}
	}

	hd24seek(currdevice,(__uint64)sectornum*512);

#if defined(LINUX) || defined(DARWIN) || defined(__APPLE__)
       long bytes=pwrite64(currdevice,buffer,WRITESIZE,(__uint64)sectornum*512); //1,devhd24);
//	cout << "BYTES=" << bytes << endl;
#endif
#ifdef WINDOWS
	DWORD dummy;
	long bytes=0;
	if (WriteFile(currdevice,buffer,WRITESIZE,&dummy,NULL)) {
		bytes=WRITESIZE;
	};
#endif
       	return bytes;
}

long hd24fs::readsectors(FSHANDLE devhd24,unsigned long sectornum,unsigned char * buffer,int sectors) 
{
	FSHANDLE currdevice=devhd24;
	// The following prints the sector num in hex:
#if (HD24FSDEBUG==1)
/*	string* x=this->p_convert->int32tohex(sectornum);
	cout << *x << endl;
	delete x; 
*/
#endif
	
//	cout << "headersectors=" << this->headersectors << "this=" <<this << endl;
	if ((this->headersectors)!=0)
	{
//		cout << "headermode enabled." << endl;
		if (sectornum<this->headersectors) 
		{
//			cout << "Headermode enabled for sector " << sectornum << endl;
			currdevice=hd24header;
		} else {
//			cout << "Headermode disabled for sector " << sectornum << endl;
		}
	} else {
//		cout << "Headermode disabled. " << sectornum << endl;
	}
       	hd24seek(currdevice,(__uint64)sectornum*SECTORSIZE);
       int READSIZE=SECTORSIZE*(sectors);
#if defined(LINUX) || defined(DARWIN)
       long bytes_read=pread64(currdevice,buffer,READSIZE,(__uint64)sectornum*512); //1,currdevice);
#endif
#ifdef WINDOWS
//	cout << "Readsectors: num="<<sectornum<<"buffer available, numsecs=" <<sectors << endl;
	DWORD bytes_read;
	//long bytes=0;
	if( ReadFile(currdevice,buffer,READSIZE,&bytes_read,NULL)) {
//		cout << "read succes"<< bytes_read << "bytes" << endl;
	} else {
//		cout << "read fail" << endl;
		bytes_read = 0;
	}
#endif
        return bytes_read;
}

long hd24fs::readsector(FSHANDLE devhd24,unsigned long sectornum,unsigned char * bootblock) 
{
	return readsectors(devhd24,sectornum,bootblock,1);
}

long hd24fs::readsector_noheader(hd24fs* currhd24,unsigned long sectornum,unsigned char * bootblock) 
{
	return readsector_noheader(currhd24->devhd24,sectornum,bootblock);
}

long hd24fs::readsector_noheader(FSHANDLE devhd24,unsigned long sectornum,unsigned char * bootblock) 
{
	unsigned long headersecs=this->headersectors;
	this->headersectors=0; // disable header processing, if applies
	long number_read=readsectors(devhd24,sectornum,bootblock,1);
	this->headersectors=headersecs; // re-enable header processing
	return number_read;
}

long hd24fs::writesector(FSHANDLE devhd24,unsigned long sectornum,unsigned char * bootblock) 
{
	return writesectors(devhd24,sectornum,bootblock,1);
}

string* hd24fs::gethd24currentdir(int argc,char* argv[]) 
{
	/* For future use. We may save a file in the
  	   homedir of the user containing info about which
 	   "path" (project/songname/file format) was last
	   selected by the user.
	*/
	
       return new string("/");
}

string* hd24fs::gethd24currentdir()
{
       return new string("/");
}

unsigned char* hd24fs::readdiskinfo() 
{
#if (HD24FSDEBUG==1)
	cout << "Driveusage before readdiskinfo=" << (int)(this->sectors_driveusage) << endl;
#endif
	// read disk info
	if (/*formatting||*/(sector_boot==NULL))
	{
		this->readbootinfo();
	}
	if (sector_diskinfo!=NULL)
	{
		memutils::myfree("readdiskinfo",sector_diskinfo);
		sector_diskinfo=NULL;
	}
	sector_diskinfo=(unsigned char *)memutils::mymalloc("readdiskinfo",1024,1);
	if (sector_diskinfo!=NULL) 
	{
		readsector(devhd24,1,sector_diskinfo); // fstfix follows
		fstfix (sector_diskinfo,512);
	}
#if (HD24FSDEBUG==1)
	cout << "Driveusage after readdiskinfo=" << (int)(this->sectors_driveusage) << endl;
#endif
	return sector_diskinfo;
}

bool hd24fs::useheaderfile(string headerfilename)
{
	getsector_bootinfo();
	if (sector_boot==NULL) 
	{
		/* we haven't got a main device yet
		   so we cannot apply a header to it */	
		return false;
	}
	// allow writing to header.
#if defined(LINUX) || defined(DARWIN)
	FSHANDLE handle=open64(headerfilename.c_str(),MODE_RDWR); //read binary
#endif
#ifdef WINDOWS
//	cout << "Mode=" << mode << endl;
	FSHANDLE handle=CreateFile(headerfilename.c_str(),MODE_RDWR,
		FILE_SHARE_READ|FILE_SHARE_WRITE,
		NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
#endif

	if (isinvalidhandle(handle)) return false;
//	cout << "Trying to enable header mode with file " << headerfilename << endl;
	hd24header=handle;
	this->headersectors=0;
	this->headersectors=getlastsectornum(hd24header)+1;
	// re-read disk info as number of projects etc can differ with header
	readsector(devhd24,1,sector_diskinfo); // fstfix follows
	fstfix (sector_diskinfo,512);

//	cout << "headersectors=" << this->headersectors << "this=" <<this << endl;
	return true;
}

void hd24fs::clearbuffer(unsigned char* buffer,unsigned int bytes)
{
	/* clear buffer */
	for (unsigned int i=0;i<bytes;i++) {
		buffer[i]=0;
	}
	return;
}

void hd24fs::clearbuffer(unsigned char* buffer)
{
	clearbuffer(buffer,512);
}


void hd24fs::cleardriveinfo(unsigned char* buffer)
{
	clearbuffer(buffer);
	string drivename="Drive Name";
	this->setname(buffer,drivename,DRIVEINFO_VOLUME_8,DRIVEINFO_VOLUME);
	return;
}

void hd24fs::useinternalboot(unsigned char* buffer,__uint32 lastsector)
{
	unsigned char internal_boot[136]=
	{
	0x54,0x41,0x44,0x41,0x54,0x53,0x46,0x20, 0x20,0x30,0x31,0x31,0x33,0xcc,0xaa,0x55,
	0x80,0x04,0x00,0x00,0x02,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
	0x02,0x00,0x00,0x00,0x03,0x00,0x00,0x00, 0x05,0x00,0x00,0x00,0x0f,0x00,0x00,0x00,
	0x2f,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
	0x63,0x00,0x00,0x00,0x63,0x00,0x00,0x00, 0x77,0x00,0x00,0x00,0x02,0x00,0x00,0x00,
	0x05,0x00,0x00,0x00,0x07,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x49,0x26,0x00,0x00,
	0x76,0x0c,0x01,0x00,0x80,0x8b,0x12,0x00, 0x1f,0x04,0x00,0x00,0xf6,0x97,0x13,0x00,
	0x14,0x89,0xb4,0x04,0x7f,0x2d,0xc9,0x04
	};

	clearbuffer(buffer);

	/* fill buffer with default boot info */
	for (unsigned int i=0;i<sizeof(internal_boot);i++) {
		buffer[i]=internal_boot[i];
	}	

	/* If a specific FS size (in sectors) was given, update boot info
	   to match that size */
	if (lastsector!=0) 
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Calculating number of clusters on the drive" << endl;
#endif
          	fstfix(buffer,512); // convert into editable format

		Convert::setint32(buffer,FSINFO_LAST_SECTOR,lastsector);
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Last sector=" << lastsector << endl;
#endif		
		// allocatable sectors=total sectors-(2*fs sectors+undo area)
		// tot secs-0x14a46b

		__uint32 allocatablesectors=lastsector-0x14a46b;
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "# allocatable sectors=" << allocatablesectors << endl;
#endif		
		Convert::setint32(buffer,FSINFO_ALLOCATABLE_SECTORCOUNT,allocatablesectors);

		// (15 sectors of drive usage info=((15*512)-8)*8 bits
		//
		__uint32 maxclusters=((15 /*sectors of alloc info*/ 
				       *512 /*bytes*/)
				       -8 /* checksum bytes */)
					*8 /* bits per byte */;
		// represents ~ 61376 allocatable clusters 
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "max # of clusters=" << maxclusters << endl;
#endif				
		__uint32 allocatableaudioblocks=(allocatablesectors - (allocatablesectors%0x480))/0x480;
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "allocatable audio blocks=" << allocatableaudioblocks << endl;
#endif				
		// given the maximum number of clusters 
		// and the total number of allocatable audio blocks,
		// we must decide on the number of audio blocks per cluster.
		__uint32 rest=0;
		if ((allocatableaudioblocks%maxclusters)>0) rest++;
		__uint32 blockspercluster=rest+((allocatableaudioblocks-(allocatableaudioblocks%maxclusters))/maxclusters);
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "blocks per cluster="<<blockspercluster<< endl;
#endif				
		Convert::setint32(buffer,FSINFO_AUDIOBLOCKS_PER_CLUSTER,blockspercluster);

		// offset 0x14h: number of audio blocks per cluster
		__uint32 allocatableclusters=(allocatableaudioblocks-(allocatableaudioblocks%blockspercluster))/blockspercluster;
		Convert::setint32(buffer,FSINFO_FREE_CLUSTERS_ON_DISK,allocatableclusters);
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "allocatableclusters="<<allocatableclusters<< endl;
#endif				
          	fstfix(buffer,512); // convert back into native format
	}	

	/* Calculate the proper checksum for the bootinfo */
	setsectorchecksum(buffer,
		0 /* startoffset */,
		0 /* sector */, 
		1 /*sectorcount */
	);
	return;
}

unsigned char* hd24fs::readbootinfo() 
{
	// read boot info

	if (sector_boot==NULL)
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Malloc space for bootsector" << endl;
#endif
		sector_boot=(unsigned char *)memutils::mymalloc("readbootinfo",1024,1);
	}

	if (sector_boot!=NULL) 
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Malloc space for bootsector succeeded" << endl;
		cout << "forcemode=" << forcemode << endl;
#endif
		if (formatting||(!forcemode)) {
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Reading sector (From disk)" << endl;
#endif
			readsector(devhd24,0,sector_boot);
		} else {             	
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Using internal boot." << endl;
#endif
			useinternalboot(sector_boot,0);	
		}
          	fstfix(sector_boot,512);
	} else {
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Malloc space for bootsector failed" << endl;
#endif
	}
#if (HD24FSDEBUG_QUICKFORMAT==1)			
	dumpsector((const char*)sector_boot);
#endif	
	return sector_boot;
}

unsigned char* hd24fs::readdriveusageinfo()
{
#if (HD24FSDEBUG==1)|| (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "hd24fs::readdriveusageinfo()" << endl;
#endif

	// read file allocation table/disk usage table
	unsigned int driveusagecount=driveusagesectorcount();
	if (sectors_driveusage==NULL)
	{

		sectors_driveusage=(unsigned char *)memutils::mymalloc("readdriveusageinfo/sectors_driveusage",512*(driveusagecount+1),1);
	}
	//cout << "ptr=" << sectors_driveusage << endl;
	if (sectors_driveusage!=NULL)
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout 	<< "hd24fs::readdriveusageinfo() reading "
		<< driveusagecount << "sectors into buffer at "
		<< &sectors_driveusage << endl;
#endif		
		readsectors(devhd24,driveusagefirstsector(),sectors_driveusage,driveusagecount);
		fstfix(sectors_driveusage,512*driveusagecount);

	}
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "Dumping newly read sector to screen:" << endl ;
	dumpsector((const char*)sectors_driveusage);
#endif
	return sectors_driveusage;
}

unsigned char* hd24fs::resetsongusage()
{
	// Reset song usage table. First we occupy all of it;
	// then we make only accessible entries available.
	if (sectors_songusage==NULL)
	{
		sectors_songusage=(unsigned char *)memutils::mymalloc("resetsongusage",512*3,1);
		if (sectors_songusage==NULL) 
		{
			return NULL;
		}
	}

	if (sectors_songusage!=NULL)
	{
		for (int i=0;i<512*3;i++) 
		{
			sectors_songusage[i]=0xff;
		}
	}

	__uint32 i;
	// table is initialized, now populate it.
	__uint32 maxprojs=this->maxprojects();
	__uint32 maxsongcount=this->maxsongsperproject();
	__uint32 totentries=maxprojs*maxsongcount; // 99 songs, 99 projects
#if (HD24FSDEBUG==1)
	cout << "Clear song usage table..."<< endl;	
	cout << "this=" << this << endl;
#endif
	for (i=0;i<totentries;i++) {
		disablebit(i,sectors_songusage);
		// this is based on song sectors. 
		// That is, entry 0=sec 0x77,
		// entry 1=sec 0x77+7, etc.
	}
#if (HD24FSDEBUG==1)
	cout << "Usage table cleared." << endl;
#endif
	return sectors_songusage;
}

unsigned char* hd24fs::resetdriveusage()
{
#if (HD24FSDEBUG==1)||(HD24FSDEBUG_QUICKFORMAT==1)
	cout << "hd24fs::resetdriveusage()" << endl;
#endif	
	// Reset drive usage table. First we occupy all of it;
	// then we make only accessible entries available.

	if (this->sectors_driveusage==NULL)
	{
		unsigned char* du=(unsigned char *)memutils::mymalloc("resetdriveusage/sectors_driveusage",512*15,1);
		sectors_driveusage=du;
		if (this->sectors_driveusage==NULL) 
		{
			return NULL;
		}
	}

	for (int i=0;i<512*15;i++) 
	{
		sectors_driveusage[i]=0xff;
	}

	if (formatting||(sector_boot==NULL) )
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "hd24fs::resetdriveusage() - reloading boot info " << endl;
#endif	

		this->readbootinfo();
	} else {
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "hd24fs::resetdriveusage() - using current (not reloading) boot info " << endl;
#endif	

	}

	__uint32 i;
	// table is initialized, now populate it.
	__uint32 totentries=Convert::getint32(sector_boot,FSINFO_FREE_CLUSTERS_ON_DISK);
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "According to superblock, free clusters on disk=" << totentries << endl;
	dumpsector((const char*)sector_boot);
#endif	
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "before reset, drive usage looks as follows: "<< endl;
	dumpsector((const char*)sectors_driveusage);
#endif	
	for (i=0;i<totentries;i++) {
		disablebit(i,sectors_driveusage);
	}
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "after reset, drive usage looks as follows: "<< endl;
	dumpsector((const char*)sectors_driveusage);
#endif	
	
#if (HD24FSDEBUG==1)
	cout << "Drive usage table cleared." << endl;
#endif
	return sectors_driveusage;
}

unsigned char* hd24fs::calcsongusage()
{
	resetsongusage();

	hd24project* currproj=NULL;
	__uint32 projcount=projectcount();
	__uint32 i;
	__uint32 j;
	for (i=1; i<=projcount;i++) 
	{
		if (currproj!=NULL) 
		{
			delete(currproj);
			currproj=NULL;
		}
		currproj=getproject(i);
		if (currproj==NULL) 
		{
			continue;
		}

		// currproj!=NULL.
		__uint32 currsongcount=currproj->songcount();
		for (j=1; j<=currsongcount;j++) 
		{
			// get song sector info.
			__uint32 songsector = currproj->getsongsectornum(j);
			if (songsector==0) 
			{
				// song at given entry is not in use 
				// in this project, no need to mark it as used.
				continue;
			}

			// mark the song used based on its entry number
			// (calculated from the sector where it lives)
			__uint32 songentry=songsector2entry(songsector);
			if (songentry!=INVALID_SONGENTRY) 
			{
				enablebit(songentry,sectors_songusage);
			}
		}

		if (currproj!=NULL)
		{
			delete(currproj);
			currproj=NULL;
		}
	}
	return sectors_songusage;
}

void hd24fs::refreshsongusage()
{
	unsigned char* songusage=calcsongusage();
	__uint32 sectornum=2; /* TODO: get from fs */
	__uint32 sectorcount=3; /* TODO: get from fs */
	fstfix(songusage,sectorcount*512);
	setsectorchecksum(songusage,
		0 /* startoffset */,
		sectornum /* sector */, 
		sectorcount /*sectorcount */
	);
	this->writesectors(this->devhd24,
			sectornum,
			songusage,
			sectorcount);
	fstfix(songusage,sectorcount*512);
	
	/* this also implies we need to update the superblock 
	   with the current song count */
	__uint32 songcount=0;
	for (int i=0;i<99*99;i++) {
		if (!(isbitzero(i,songusage)))
		{
			songcount++;
		}
	};
	songsondisk(songcount);
	fstfix(sector_boot,512);
	setsectorchecksum(sector_boot,
		0 /* startoffset */,
		0 /* sector */, 
		1 /*sectorcount */);
	this->writesectors(this->devhd24,
			0,
			sector_boot,
			1);
	fstfix(sector_boot,512);
	return;
}

unsigned char* hd24fs::getsector_diskinfo() 
{
	getsector_bootinfo();
	unsigned char* targetbuf=sector_diskinfo;
	if (/*formatting||*/(sector_diskinfo==NULL) )
	{
		targetbuf=readdiskinfo();
	}
	return sector_diskinfo;
}

unsigned char* hd24fs::getsector_bootinfo() 
{
	unsigned char* targetbuf=sector_boot;
	if (/*formatting||*/(sector_boot==NULL) )
	{
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Re-reading bootinfo now." << endl;
#endif
		targetbuf=readbootinfo();
	}
	return targetbuf;
}

unsigned char* hd24fs::getsectors_driveusage()
{
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "hd24fs::getsectors_driveusage()" << endl;
#endif
	
	readbootinfo();
	if (sectors_driveusage==NULL)
	{
		sectors_driveusage=readdriveusageinfo();
	}
	return sectors_driveusage;
}

unsigned char* hd24fs::getcopyofusagetable()
{
	unsigned char* copyusagetable=(unsigned char*)memutils::mymalloc("copyusagetable",15*512,1);
	if (copyusagetable==NULL) 
	{
		/* Out of memory */
		return NULL;
	}

	// copy current drive usage table to a copy;
	readdriveusageinfo();
	int i;
	for (i=0;i<(512*15);i++) {
		copyusagetable[i]=sectors_driveusage[i];
	}
	return copyusagetable;
}

string* hd24fs::volumename() 
{	
	if (!(isOpen())) 
	{
	      	return new string("");
	}
	getsector_diskinfo();
	return Convert::readstring(sector_diskinfo,DRIVEINFO_VOLUME,64);
}

void hd24fs::setvolumename(string newname)
{
	if (sector_diskinfo==NULL)
	{
		readdiskinfo();
	}
	this->setname(sector_diskinfo,newname,DRIVEINFO_VOLUME_8,DRIVEINFO_VOLUME);
	return;
}

unsigned long hd24fs::driveusagesectorcount()
{
	if (!(isOpen())) 
	{	
		cout << "FS not open!";
		return 0;
	}
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Figuring out number of sectors used for drive usage"
		<< endl;
#endif
	
	getsector_bootinfo();
	return Convert::getint32(sector_boot,FSINFO_NUMSECTORS_DRIVEUSAGE);
}

unsigned long hd24fs::clustercount()
{
	/* 
           Clustercount=
		(number of allocatable sectors on disk)/
                ((sectors per audioblock)*(audioblocks per cluster))
        */
	if (!(isOpen())) 
	{
		return 0;
	}
	getsector_bootinfo();
	__uint32 allocatablesectorcount=
	    Convert::getint32(sector_boot,FSINFO_ALLOCATABLE_SECTORCOUNT);
	__uint32 audioblocksize=
	    Convert::getint32(sector_boot,FSINFO_BLOCKSIZE_IN_SECTORS);
        __uint32 clustersize=
 	    Convert::getint32(sector_boot,FSINFO_AUDIOBLOCKS_PER_CLUSTER)
            *audioblocksize;

        allocatablesectorcount-=(allocatablesectorcount%clustersize);
	return allocatablesectorcount/clustersize; 
}

void hd24fs::dumpclusterusage(unsigned char* usagebuffer)
{
	if (!(isOpen())) 
	{
		return;
	}
	__uint32 clusters=clustercount();
	for (__uint32 i=0;i<clusters;i++) {
		if (isfreecluster(i,usagebuffer)) {
			cout << "0";
		} else {
			cout << "1";
		}
	}
	cout <<endl;
	return;
}

void hd24fs::dumpclusterusage2(unsigned char* usagebuffer)
{
	__uint32 clusters=clustercount();
	__uint32 currpos=0;
	cout << "DumpClusterUsage2" << endl;
	while (currpos<clusters) {
		__uint32 blockstart=currpos;
		while (isfreecluster(blockstart,usagebuffer) && (blockstart<clusters)) {
			blockstart++;
		}
//		cout << "Block starts at cluster " <<blockstart << endl;
		if (blockstart==clusters) {
			break;
		}

		// blockstart now points to a nonfree cluster
		__uint32 blockend=blockstart;
		while (!isfreecluster(blockend,usagebuffer) && (blockend<clusters)) {
			blockend++;
		}
		// blockend now points to a free cluster
		currpos=blockend;
		__uint32 blocklen=blockend-blockstart;
		printf("%x %x\n",(unsigned int) cluster2sector(blockstart),(unsigned int)( getblockspercluster()*blocklen ));
	}	
}

unsigned long hd24fs::driveusagefirstsector()
{
	if (!(isOpen())) 
	{
		return 0;
	}
	getsector_bootinfo();

	return Convert::getint32(sector_boot,FSINFO_STARTSECTOR_DRIVEUSAGE);
}

unsigned char* hd24fs::findorphanclusters()
{
	if (!(isOpen())) 
	{
		return NULL;
	}
	__uint32 driveusagecount=driveusagesectorcount();
	getsectors_driveusage();
	int numprojs=projectcount();

	if (sectors_orphan==NULL) { 
		// only allocate once (free on object destruct)
		sectors_orphan=(unsigned char *)memutils::mymalloc("findorphanclusters",512*(driveusagecount+1),1);
	}
	readsectors(devhd24,driveusagefirstsector(),sectors_orphan,driveusagecount);
	fstfix(sectors_orphan,512*driveusagecount);
	
	for (int proj=1; proj<=numprojs; proj++) {
		hd24project* currproj=this->getproject(proj);
		int numsongs=currproj->songcount();
		for (int song=1; song<=numsongs; song++) {
			hd24song* currsong=currproj->getsong(song);
			if (currsong==NULL) continue;
			currsong->unmark_used_clusters(sectors_orphan);	
			delete currsong;
		}
		if (currproj!=NULL) {
			delete currproj;		
			currproj=NULL;
		}
	}
	return sectors_orphan;
}

bool hd24fs::isbitzero(unsigned long i,unsigned char* usagebuffer)
{
	int bitnum=i%32;
	i-=bitnum;
	i/=32;	// i now is word num
	i*=4;	// i now is offset
	__uint32 getword=Convert::getint32(usagebuffer,i);
	__uint32 mask=1;
#if (HD24FSDEBUG_BITSET==1)
	cout << "bitnum=" << bitnum << " ";
#endif	
	mask=mask<<bitnum;
	__uint32 bitval=(getword & mask);
#if (HD24FSDEBUG_BITSET==1)
	cout << "bitval=" << bitval << endl;
#endif
	if (bitval == 0) return true;
	return false;
}

void hd24fs::enablebit(__uint32 ibitnum,unsigned char* usagebuffer) 
{
#if (HD24FSDEBUG_BITSET==1)
	cout << "enable bit " << ibitnum << endl;
#endif
	int bitnum=ibitnum%32;
	ibitnum-=bitnum;
	ibitnum/=32;	// i now is word num
	ibitnum*=4;	// i now is byte offset of word
	__uint32 getword=Convert::getint32(usagebuffer,ibitnum);
	__uint32 mask=1;
	mask=mask<<bitnum;
#if (HD24FSDEBUG_BITSET==1)
	cout << "getword=" << getword << "mask=" << mask << endl;
#endif		
	getword=getword|mask;
	Convert::setint32(usagebuffer,ibitnum,getword);
}

void hd24fs::disablebit(__uint32 ibitnum,unsigned char* usagebuffer)
{
#if (HD24FSDEBUG_BITSET==1)
	cout << "disable bit " << ibitnum << endl;
#endif
	int bitnum=ibitnum%32;
	ibitnum-=bitnum;
	ibitnum/=32;	// i now is word num
	ibitnum*=4;	// i now is offset
	__uint32 getword=Convert::getint32(usagebuffer,ibitnum);
	__uint32 mask=1;
	mask=mask<<bitnum;
#if (HD24FSDEBUG_BITSET==1)
	cout << "getword=" << getword << "mask=" << mask << endl;
#endif	
	getword=getword& (0xFFFFFFFF ^ mask);
#if (HD24FSDEBUG_BITSET==1)
	cout << "new getword=" << getword << endl;
#endif		
	Convert::setint32(usagebuffer,ibitnum,getword);
}

bool hd24fs::isfreecluster(unsigned long i,unsigned char* usagebuffer) 
{
	return isbitzero(i,usagebuffer);
}

void hd24fs::allocatecluster(__uint32 clusternum,unsigned char* usagebuffer) 
{
	enablebit(clusternum,usagebuffer);
}

void hd24fs::freecluster(__uint32 clusternum,unsigned char* usagebuffer) 
{
	disablebit(clusternum,usagebuffer);
}
void hd24fs::allocatecluster(__uint32 clusternum) 
{
	allocatecluster(clusternum,sectors_driveusage);
}

void hd24fs::freecluster(__uint32 clusternum) 
{
	freecluster(clusternum,sectors_driveusage);
}

unsigned long hd24fs::freeclustercount() 
{
	if (!(isOpen())) 
	{
		return 0;
	}
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "hd24fs::freeclustercount()" << endl;
#endif
	
	sectors_driveusage=getsectors_driveusage();
	
	if (sectors_driveusage==NULL) 
	{
		return 0; // cannot get driveusage sectors, 0 clusters free.
	}
	unsigned long i=0;
	__uint32 fsc=driveusagesectorcount();
	
	if (fsc>0xFF) return 0;
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Sectors used for drive usage=" << fsc << endl;
#endif
	__uint32 clusters=((fsc /*sectors of alloc info*/ 
				       *512 /*bytes*/)
				       -8 /* checksum bytes */)
					*8 /* bits per byte */;
	//unsigned long clusters=((512*fsc-1)+504)*8;
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Total clusters=" << clusters << endl;
#endif
	
	unsigned long freeclusters=0;
	for (i=0;i<clusters;i++) {
		if (isfreecluster(i,sectors_driveusage)) 
		{
#if (HD24FSDEBUG_QUICKFORMAT==1)
		cout << "Cluster " << i << " is free" << endl;
#endif			
			freeclusters++;
		}
	}
	return freeclusters;
}

string* hd24fs::freespace(unsigned long rate,unsigned long tracks) 
{
	if (!(isOpen())) 
	{
		return new string("");
	}

	unsigned long freeclusters=freeclustercount();
#if (HD24FSDEBUG_QUICKFORMAT==1)	
	cout << "free clusters=" << freeclusters << endl;
#endif	
	__uint64 freesectors=freeclusters*getblocksizeinsectors()*getblockspercluster();
#if (HD24FSDEBUG_QUICKFORMAT==1)	
	cout << "free sectors=" << freesectors << endl;
#endif	
	__uint64 freebytes=freesectors*SECTORSIZE;
#if (HD24FSDEBUG_QUICKFORMAT==1)	
	cout << "free bytes=" << freesectors << endl;
#endif	
	__uint64 freesamples=(__uint64)(freebytes/3);
#if (HD24FSDEBUG_QUICKFORMAT==1)
	cout << "free samples=" << freesamples << endl;
#endif
	__uint64 freeseconds=(__uint64)(freesamples/rate/tracks);
	unsigned long freehours=(freeseconds-(freeseconds%3600))/3600;
	freeseconds-=(freehours*3600);
	unsigned long freeminutes=(freeseconds-(freeseconds%60))/60;
	freeseconds-=(freeminutes*60);
       	string* newst=Convert::int2str(freehours);
	*newst+=" hr ";
	string* freemins=Convert::int2str(freeminutes,2,"0");
	*newst+=*freemins;
	delete freemins;
	*newst+=" min ";
	string* freesecs=Convert::int2str(freeseconds,2,"0");
	*newst+=*freesecs;
	delete freesecs;
	*newst+=" sec ";
      	return newst; // throw exception?
}

string* hd24fs::version() 
{
	if (!(isOpen())) 
	{
		return new string("");
	}
	getsector_bootinfo();
	string* newst=Convert::readstring(sector_boot,FSINFO_VERSION_MAJOR,1);
	*newst+=".";
	string* dummy=Convert::readstring(sector_boot,FSINFO_VERSION_MINOR,2);
	*newst+=*dummy;
	delete dummy;
	return newst;
}

unsigned long hd24fs::maxprojects() 
{
	if (!(isOpen())) 
	{
	      	return 0;
	}
	getsector_bootinfo();
	unsigned long maxprojs=Convert::getint32(sector_boot,FSINFO_MAXPROJECTS);
	if (maxprojs>99) {
		maxprojs=99; 
		/* safety feature while no larger project
                   counts are known to be valid; gives 
		   more stability when working with corrupt drives */
		this->writeprotected=true;
	}
	return maxprojs;
}

unsigned long hd24fs::getblocksizeinsectors() 
{
	if (!(isOpen())) 
	{
	      	return 0;
	}
	getsector_bootinfo();
	if (forcemode) {
		return 0x480;
	}
	unsigned long blocksize=Convert::getint32(sector_boot,FSINFO_BLOCKSIZE_IN_SECTORS);
	if (blocksize!=0x480)
	{
		this->writeprotected=true;
	}
	return blocksize;
}

unsigned long hd24fs::getbytesperaudioblock()
{
	return getblocksizeinsectors()*512;
}

unsigned long hd24fs::getblockspercluster() 
{
	if (!(isOpen())) 
	{
	      	return 0;
	}
	getsector_bootinfo();
	unsigned long maxprojs=Convert::getint32(sector_boot,FSINFO_AUDIOBLOCKS_PER_CLUSTER);
	return maxprojs;
}

unsigned long hd24fs::maxsongsperproject() 
{
	if (!(isOpen())) 
	{
	      	return 0;
	}
	getsector_bootinfo();
	unsigned long maxsongs=Convert::getint32(sector_boot,FSINFO_MAXSONGSPERPROJECT);
	return maxsongs;
}

__uint32 hd24fs::getprojectsectornum(__uint32 i) 
{
#if (HD24FSDEBUG==1)
	cout << "hd24fs::getprojectsectornum("<<i<<")"<< endl;
#endif
	// 1-based project sectornum
	if (!(isOpen())) 
	{
	      	return 0;
	}
	if (i<1)
	{
		return 0;
	}
	if (i>maxprojects())
	{
		return 0;
	}
	getsector_diskinfo();
	unsigned long projsec=Convert::getint32(sector_diskinfo,	
			DRIVEINFO_PROJECTLIST+((i-1)*4));
	
#if (HD24FSDEBUG==1)
	cout << "projsec = " << projsec << endl;
#endif
	return projsec;
}

void hd24fs::lastprojectid(signed long projectid)
{
	if (!(isOpen())) 
	{
	      	return;
	}
	getsector_diskinfo();
	__uint32 lastprojsec=getprojectsectornum(projectid);
	if (lastprojsec==0) {
		return;
	}
	if (projectid==lastprojectid())
	{
		// nothing changed- nothing to save
		return;
	}

	Convert::setint32(sector_diskinfo,DRIVEINFO_LASTPROJ,lastprojsec);
	savedriveinfo();
	return;
}

signed long hd24fs::lastprojectid() 
{
	if (!(isOpen())) 
	{
	      	return -1;
	}
	getsector_diskinfo();
	unsigned long lastprojsec=Convert::getint32(sector_diskinfo,DRIVEINFO_LASTPROJ);
	if (lastprojsec==0) {
		// TODO: This differs from the real HD24 where even
		// on a freshly formatted drive there always is at least
		// one project.
		return -1;
	}
	int i;
	int maxprojs=maxprojects();
	for (i=1;i<=maxprojs;i++) 
	{
		unsigned long projsec=getprojectsectornum(i);

		if (projsec==lastprojsec) 
		{
			return i;
		}
	}
	// no default project. hm......
	if (maxprojs>=1) {
		return 1;
	}
	return -1;
}

__uint32 hd24fs::getunusedsongsector()
{
	if (!(isOpen())) 
	{
	      	return 0; // return 0- this is an invalid songsector
			  // so error is detectable
	}

	// generate an up-to-date song usage table.
	unsigned char* songusage=calcsongusage();

	int currsongentry=0;
	signed long foundentry=-1;
	int maxprojs=this->maxprojects();
	int maxsongcount=this->maxsongsperproject();
	int totentries=maxprojs*maxsongcount; // 99 songs, 99 projects
	while (currsongentry<totentries) // 99 sec, 99 proj
	{
		if (isbitzero(currsongentry,songusage)) {
			foundentry=currsongentry;
			break;
		}
		currsongentry++;
	}
	if (foundentry==-1)
	{
		return 0;
	}
	return songentry2sector(foundentry);
}

void hd24fs::allocsongentry(unsigned long songentry) 
{
	enablebit(songentry,sectors_songusage);
}

unsigned long hd24fs::projectcount() 
{
	if (!(isOpen())) 
	{
	      	return 0;
	}
	getsector_diskinfo();
	unsigned long lastprojsec=Convert::getint32(sector_diskinfo,DRIVEINFO_LASTPROJ);
	if (lastprojsec==0) 
	{
		return 0;
	}
	__uint32 projcount=Convert::getint32(sector_diskinfo,DRIVEINFO_PROJECTCOUNT);
	if (projcount>maxprojects()) return maxprojects();

	return projcount;
}

int hd24fs::mode() {
	return p_mode;
}
	
hd24project* hd24fs::getproject(__sint32 projectid) 
{
	__uint32 projsec=getprojectsectornum(projectid); // 1-based
	if (projsec==0) {
		return NULL;
	}
	return new hd24project(this,projectid);
}

hd24project* hd24fs::createproject(const char* projectname)
{
#if (HD24FSDEBUG==1)
	cout << "hd24fs::createproject(" << projectname << ")" << endl;
//	cout << "Driveusage before createproject=" << (int)(this->sectors_driveusage) << endl;
#endif
	/* This creates a new project (with given project name)
	   on the drive (if possible).
           NULL is returned when unsuccessful, a pointer to the
           project otherwise.
        */
#if (HD24FSDEBUG==1) 
	cout << "hd24fs asked to create project " << projectname << endl;
#endif
	int i;
	// find first project with project sector num 0!
	int maxprojs=maxprojects();

	getsector_bootinfo();
	if (sector_boot==NULL) {
		// unknown cluster size.
		return 0;
	}
	__uint32 firstprojsec=Convert::getint32(sector_boot,FSINFO_FIRST_PROJECT_SECTOR);
	cout << "Firstprojsec="<< firstprojsec << endl;
	__uint32 secsperproj=Convert::getint32(sector_boot,FSINFO_SECTORS_PER_PROJECT);
	cout << "Sectors per project="<< secsperproj << endl;

	// Let's calculate a list of unused project sectors
	char* projused=(char*)memutils::mymalloc("createproject",maxprojs,1);
	if (projused==NULL) {
		return 0; // out of memory
	}

	for (i=0;i<maxprojs;i++) {
		projused[i]=0;
	}

	for (i=1;i<=maxprojs;i++) { 
		__uint32 projsec=getprojectsectornum(i); // 1-based
		if (projsec!=0)
		{
			/* projects do not necessarily have to 	
                           be stored on disk in the same order 
                           as their project numbers- 
			   so project 1 can be at sector 0x15
                           while project 2 is at sector 0x14.
	 		   This is why we have to convert project 
                           sector to project slot. The cast to int
                           makes sure we don't accidentally end up
                           with a float index that can be misinterpreted. */
			projused[(int)((projsec-firstprojsec)/secsperproj)]=1;
		}
	}

	int foundslotnum=0;
	for (i=1;i<=maxprojs;i++) 
	{
		__uint32 projsec=getprojectsectornum(i); // 1-based

		if (projsec==0) 
		{
			foundslotnum=i;
			break;
		}
	}
	
	// Now find an unused project sector
	__uint32 foundsecnum=0;
	for (i=0;i<maxprojs;i++) {
		if (projused[i]==0) {
			foundsecnum=(i*secsperproj)+firstprojsec;
			break;
		}
	}
	memutils::myfree("projused",projused);

	if (foundslotnum==0) 
	{
		// no unused slots.
		return NULL;
	}
	__uint32 projectid=foundslotnum;
	foundslotnum--;	// use 0-based slot num

	if (foundsecnum==0) {
		// no unsused project sectors found.
		// This is seriously fishy as there *are*
		// unused slots- so that should never happen.
		// Looks like we're dealing with a corrupt FS!
		this->writeprotected=true;
		return NULL;			
	}
	// Now to assign the first unused project sector 
	// to the first unused project slot.

	// First, update the drive info.
	getsector_diskinfo();

	// Add the new project pointer to the disk info:
	Convert::setint32(sector_diskinfo,DRIVEINFO_PROJECTLIST+(foundslotnum*4),foundsecnum);
	Convert::setint32(sector_diskinfo,DRIVEINFO_LASTPROJ,foundsecnum);

	Convert::setint32(sector_diskinfo,DRIVEINFO_PROJECTCOUNT,
	Convert::getint32(sector_diskinfo,DRIVEINFO_PROJECTCOUNT)+1);

	bool isnew=true;
	hd24project* newproject=new hd24project(this,projectid,foundsecnum,projectname,isnew);
	savedriveinfo();

	return newproject;
}

bool hd24fs::isallinput()
{
	return this->allinput;
}

void hd24fs::setallinput(bool p_allinput)
{
	this->allinput=p_allinput;
}

void hd24fs::setallinput(void)
{
	this->setallinput(true);
}

/* These three functions are for the 'auto input' button
   (having to do with automatic toggling of monitoring 
    between 'tape' and inputs during a punch in */
bool hd24fs::isautoinput()
{
	return this->autoinput;
}

void hd24fs::setautoinput(bool p_autoinput)
{
	this->autoinput=p_autoinput;
}

void hd24fs::setautoinput(void)
{
	this->setautoinput(true);
}

void hd24fs::writebackupblock(__uint32 p_sector,__uint32 p_blocksize,
			      __uint32 lastsec,bool fullcommit)
{
	/** Used by commit. This writes a logical block 
            of file system data to the end of the drive. */
        unsigned char backbuf[1024];

	__uint32 i;
	__uint32 blocksize=p_blocksize;
	
	if (fullcommit==false)
	{
		// we're doing a quick commit, so only backup
		// changed blocks.
		if (p_sector>highestFSsectorwritten) return;
	}
	
	for (i=1;i<=blocksize;i++) {
		// read sector $sector+$i-1
		// write to sector -($sector+1+$blocksize-$i)
		// 	(where -1= last sector)
		__uint32 currentsourcesector=p_sector+(i-1);
		
		readsector_noheader(this, currentsourcesector, backbuf);		
		__uint32 targetsector=(lastsec-(p_sector+1+blocksize-i))+1;
	//	cout << "write sec " << targetsector << endl;
		writesector(this->devhd24,targetsector,backbuf);
	}
}

bool hd24fs::commit()
{
	// default commit is a quick commit rather than full commit.
	// A quick commit only commits sectors up to the last project/song
	// sector changed.
	return this->commit(false);
}
bool hd24fs::commit(bool fullcommit)
{
	/** This creates a backup of the file system to the end of the drive. */
	
	
#if (HD24FSDEBUG==1)
	cout << "hd24fs::commit()" << endl;
//	cout << "Driveusage before commit=" << (int)(this->sectors_driveusage) << endl;
#endif
	if (this->headersectors!=0)
	{
		// ehm. Obviously we're not going to overwrite the
		// end of the drive with header file information,
		// as that would defeat the purpose of header files
		// (which is to allow safe read-only operation).
		return true;
	};
	__uint32 sector=0;
	__uint32 blocksize=1;
	__uint32 count=1;
	__uint32 lastsec=getlastsectornum();
	writebackupblock(sector,blocksize,lastsec,fullcommit); // backup superblock

	sector+=(blocksize*count);
	blocksize=1;
	count=1;

	writebackupblock(sector,blocksize,lastsec,fullcommit); // backup drive info

	sector+=(blocksize*count);
	blocksize=3;
	count=1;
	writebackupblock(sector,blocksize,lastsec,fullcommit); // Backup undo (?) usage

	sector+=(blocksize*count);
	blocksize=15;
	count=1;
	writebackupblock(sector,blocksize,lastsec,fullcommit); // Backup drive usage table

	sector+=(blocksize*count);
	blocksize=1;
	count=99;

	__uint32 i;
	for (i=1;i<=count;i++) 
	{
#if (HD24FSDEBUG_COMMIT==1)
	cout <<"Going to write proj backup block no. " << i << endl;
#endif
		writebackupblock(sector+(i-1),blocksize,lastsec,fullcommit); // Backup project 
	}

	sector+=(blocksize*count);
	count=99*99;
	for (i=1;i<=count;i++) 
	{
#if (HD24FSDEBUG_COMMIT==1)
	cout <<"Going to write song backup block no. " << i << endl;
#endif
		blocksize=2;
		writebackupblock(sector+(7*(i-1)),blocksize,lastsec,fullcommit); // Backup song

		blocksize=5;
		writebackupblock(sector+(7*(i-1))+2,blocksize,lastsec,fullcommit); // Backup song alloc info
	}
#if (HD24FSDEBUG_COMMIT==1)
	cout <<"Wrote backup blocks" << endl;
	cout << "Driveusage after commit=" << (int)(this->sectors_driveusage) << endl;
#endif
	highestFSsectorwritten=0; // reset 
	return true;
}

long unsigned int hd24fs::setsectorchecksum(unsigned char* buffer,unsigned int startoffset,unsigned int startsector,unsigned int sectors)
{
	// Calculates and sets the checksum for a block of data.
	// Data must be in drive-native format.
	long unsigned int checksum32 = 0;
	unsigned long int totbytes=(SECTORSIZE*sectors);

	buffer[startoffset+totbytes-8]=startsector%256;
	buffer[startoffset+totbytes-7]=(startsector>>8)%256;
	buffer[startoffset+totbytes-6]=255-	buffer[startoffset+totbytes-8];
	buffer[startoffset+totbytes-5]=255-	buffer[startoffset+totbytes-7];

	for (unsigned long i = 0; i < totbytes; i += 4) 
	{
		unsigned long num = Convert::getint32(buffer, i+startoffset);
		int byte1 = num % 256;
		int byte2 = (num >> 8) % 256;
		int byte3 = (num >> 16) % 256;
		int byte4 = (num >> 24) % 256;
		num = byte4 + (byte3 << 8) + (byte2 << 16) + (byte1 << 24);
		checksum32 += num;
	}
	unsigned long oldchecksum=0;
	oldchecksum+=((unsigned char)(buffer[startoffset+totbytes-1])); oldchecksum=oldchecksum <<8;
	oldchecksum+=((unsigned char)(buffer[startoffset+totbytes-2])); oldchecksum=oldchecksum <<8;
	oldchecksum+=((unsigned char)(buffer[startoffset+totbytes-3])); oldchecksum=oldchecksum <<8;
	oldchecksum+=((unsigned char)(buffer[startoffset+totbytes-4])); 
	oldchecksum-=checksum32;
	buffer[startoffset+totbytes-4]=oldchecksum%256; oldchecksum=oldchecksum >> 8;
	buffer[startoffset+totbytes-3]=oldchecksum%256; oldchecksum=oldchecksum >> 8;
	buffer[startoffset+totbytes-2]=oldchecksum%256; oldchecksum=oldchecksum >> 8;
	buffer[startoffset+totbytes-1]=oldchecksum%256; oldchecksum=oldchecksum >> 8;
	return checksum32;
}

void hd24fs::savedriveinfo()
{
	// This is capable of handling only 1-sector-per-project projects
	__uint32 driveinfosector=1;
	if (sector_diskinfo==NULL)
	{
		// diskinfo is not available, nothing to do.
		return;
	}
#if (HD24FSDEBUG==1)
	cout << "FSTFIX" << endl;
#endif	
	this->fstfix(sector_diskinfo,512); // sector is now once again in native format

#if (HD24FSDEBUG==1)
	cout << "set checksum" << endl;
#endif	
	this->setsectorchecksum(sector_diskinfo,0,driveinfosector,1);     
#if (HD24FSDEBUG==1)
	cout << "write sectors" << endl;
#endif	
	this->writesectors(this->devhd24,
			driveinfosector,
			sector_diskinfo,1);
	
#if (HD24FSDEBUG==1)
	cout << "unfix" << endl;
#endif	
	this->fstfix(sector_diskinfo,512); // sector is now in 'fixed' format
#if (HD24FSDEBUG==1)
	cout << "commit" << endl;
#endif	
	this->commit();
}

void hd24fs::setname(unsigned char* namebuf,string newname,__uint32 shortnameoff,__uint32 longnameoff)
{
	/** Used for setting song/project/drive names 
            Long name is up to 64 characters; short name 
            is up to 10 chars.
        */
#if (HD24FSDEBUG==1)
	cout	<< "hd24fs::setname("
		<< "*namebuf=" << *namebuf << ","
		<< "newname=" << newname << ","
		<< "shortnameoff="<<shortnameoff << ","
		<< "longnameoff=" << longnameoff <<");" << endl;
#endif		
	bool foundzero=false;
	for (__uint32 i=0;i<64;i++) 
	{
		if (!foundzero) 
		{
			namebuf[longnameoff+i]=newname.c_str()[i];
			if (namebuf[longnameoff+i]==0) {
				foundzero=true;
#if (HD24FSDEBUG==1)
				cout << "Found zero at " << i << endl;
#endif
			}
		}
		else 
		{
			namebuf[longnameoff+i]=0;
		}
	}
	// Now set FST 1.0 short name
	unsigned char* target=namebuf+shortnameoff;	
	foundzero=false;
	__uint32 count=0;
	for (__uint32 i=0;i<10;i++) 
	{
		if (!foundzero)
		{
			target[count]=newname.c_str()[i];
			if (target[count]==0) 	
			{
				foundzero=true;
			}
		}
		else
		{
			target[count]=0x20; /* short name is filled out
					       with spaces */
					
		}
		count++;
		if (count==8) 
		{
			count=0;
			target+=10;
		}
	}
	return;
}

void hd24fs::savedriveusage()
{
	__uint32 driveusagesector=5;
	__uint32 totsectors=15;
	this->fstfix(sectors_driveusage,totsectors*512); // sector is now once again in native format

	this->setsectorchecksum(sectors_driveusage,0,driveusagesector,totsectors);
	this->writesectors(this->devhd24,
			driveusagesector,
			sectors_driveusage,totsectors);
	
	this->fstfix(sectors_driveusage,totsectors*512); // sector is now in 'fixed' format
#if (HD24FSDEBUG==1)
	cout << "free cluster count=" << freeclustercount() << endl;
#endif
	unsigned char* bootrec=readbootinfo();
	// update FSINFO_FREE_CLUSTERS_ON_DISK	
	
	Convert::setint32(bootrec,FSINFO_FREE_CLUSTERS_ON_DISK,freeclustercount());
	fstfix(bootrec,512); // convert back into native format

	/* Calculate the proper checksum for the bootinfo */
	setsectorchecksum(bootrec,
		0 /* startoffset */,
		0 /* sector */, 
		1 /*sectorcount */
	);
	this->writesectors(this->devhd24, 0,bootrec,1);
	fstfix(bootrec,512); // convert back into fixed format
	this->commit();
}


__uint32 hd24fs::writesuperblock(__uint32 lastsec)
{
	// writes a new superblock to an unformatted drive.
	//
	// normal start of data area=1397f6
	// size of 1 audio block=0x480 sectors
	// fs size=0x77+7*99
	// so minimum usable drive is 0x1397f6+0x480+(0x77+(7*99*99))
	// =0x14a8ec sectors
	if (lastsec<0x14a8ec)
	{
		// drive is smaller than the minimum needed for 
		// storing at least 1 audio block.
		return RESULT_FAIL;
	}
	unsigned char superblock[512];
	useinternalboot(superblock,lastsec); // this automatically sets sector checksum
	writesectors(this->devhd24,0,&superblock[0],1);
#if (HD24FSDEBUG_QUICKFORMAT==1)	

	cout << "Writing superblock." << endl;
	dumpsector((const char*)superblock);

#endif

	force_reload();

	readbootinfo();
	
#if (HD24FSDEBUG_CLUSTERddCALC==1)	
	cout << "Displaying sector after reload." << endl;
	dumpsector((const char*)sector_boot);
#endif

	return RESULT_SUCCESS;
}

void hd24fs::force_reload()
{
#if (HD24FSDEBUG==1)
	cout << "Free superblock mem" << endl;
#endif
	if (sector_boot!=NULL)
	{
		memutils::myfree("sectors_boot",sector_boot);
		sector_boot=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free diskinfo mem" << endl;
#endif
	if (sector_diskinfo!=NULL) 
	{
		memutils::myfree("sectors_diskinfo",sector_diskinfo);
		sector_diskinfo=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free drive usage mem" << endl;
#endif
	if (sectors_driveusage!=NULL)
	{
		memutils::myfree("sectors_driveusage",sectors_driveusage);
		sectors_driveusage=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free orphan sectors mem" << endl;
#endif
	if (sectors_orphan!=NULL)
	{
		memutils::myfree("sectors_orphan",sectors_orphan);
		sectors_orphan=NULL;
	}
#if (HD24FSDEBUG==1)
	cout << "Free song usage sectors mem" << endl;
#endif
	if (sectors_songusage!=NULL)
	{
		memutils::myfree("sectors_songusage",sectors_songusage);
		sectors_songusage=NULL;
	};
		
}
__uint32 hd24fs::writedriveinfo()
{
	readdiskinfo();
	cleardriveinfo(sector_diskinfo);
	fstfix(sector_diskinfo,512); // back into native format
	writesectors(this->devhd24,1,sector_diskinfo,1);
	if (sector_diskinfo!=NULL) {
		memutils::myfree("sector_diskinfo",sector_diskinfo);
		sector_diskinfo=NULL; // force re-read
	}
	hd24project* firstproject=createproject("Proj Name");
	memutils::myfree("firstproject",firstproject);
	
	if (sector_diskinfo!=NULL) {
		memutils::myfree("sector_diskinfo",sector_diskinfo);
		sector_diskinfo=NULL; // force re-read
	}
	__uint32 psec=getprojectsectornum(1);
	if (sector_diskinfo!=NULL) {
		memutils::myfree("sector_diskinfo",sector_diskinfo);
		sector_diskinfo=NULL; // force re-read
	}
	readdiskinfo();
	Convert::setint32(sector_diskinfo,DRIVEINFO_LASTPROJ,psec);
	savedriveinfo();
	
	return RESULT_SUCCESS;
}

__uint32 hd24fs::writesongusage()
{
	unsigned char* buffer=resetsongusage();
	if (buffer==NULL)
	{
		return RESULT_FAIL;
	}
	__uint32 sectornum=2; 
	__uint32 sectorcount=3; 
	fstfix(buffer,sectorcount*512);
	setsectorchecksum(buffer,
		0 /* startoffset */,
		sectornum /* sector */, 
		sectorcount /*sectorcount */
	);
	this->writesectors(this->devhd24,
			sectornum,
			buffer,
			sectorcount);
	fstfix(buffer,sectorcount*512);
	return RESULT_SUCCESS;
}

__uint32 hd24fs::writedriveusage()
{
	if (sectors_driveusage!=NULL)
	{
		memutils::myfree("sectors_driveusage",sectors_driveusage);
		sectors_driveusage=NULL;
	}
	
	unsigned char* buffer=resetdriveusage();
	if (buffer==NULL)
	{
		return RESULT_FAIL;
	}
	__uint32 sectornum=5; 
	__uint32 sectorcount=15; 
	fstfix(buffer,sectorcount*512);
	setsectorchecksum(buffer,
		0 /* startoffset */,
		sectornum /* sector */, 
		sectorcount /*sectorcount */
	);

	this->writesectors(this->devhd24,
			sectornum,
			buffer,
			sectorcount);
	fstfix(buffer,sectorcount*512);
	
	return RESULT_SUCCESS;
}

__uint32 hd24fs::quickformat(char* message)
{
	// This procedure performs a quickformat on the current drive.
	// There is no need for the drive to be a valid HD24 drive
	// for this to work.
	// Safety confirmations etc. are considered to be the
	// responsibility of the caller.
	
	gotlastsectornum=false; // force re-finding last sector num
	__uint32 lastsec=getlastsectornum();
	
	formatting=true;
	
	if (lastsec==0)
	{
		if (message!=NULL) strcpy(message,(const char*)&"Lastsec=0");
		return 0;
	}
	__uint32 result=writesuperblock(lastsec);

	if (result==RESULT_FAIL)
	{
		if (message!=NULL) strcpy(message,(const char*)&"Write superblock failed");
		return 0; // lastsec 0 means failed format
	}

	result=writedriveinfo();
	if (result==RESULT_FAIL)
	{
		if (message!=NULL) strcpy(message,(const char*)&"Write driveinfo failed");
		return 0; // lastsec 0 means failed format
	}

	result=writesongusage();
	if (result==RESULT_FAIL)
	{
		if (message!=NULL) strcpy(message,(const char*)&"Write song usage failed");
		return 0; // lastsec 0 means failed format
	}

	result=writedriveusage();
	if (result==RESULT_FAIL)
	{
		if (message!=NULL) strcpy(message,(const char*)&"Write drive usage failed");
		return 0; // lastsec 0 means failed format
	}

	// write empty song-entry usage table
	// write empty drive usage table
	// write 99 empty projects
	// create default project
	// (write 99*99 empty songs)
	// (empty audio space)
	// commit fs
	commit();
	formatting=false;
	force_reload();
	return lastsec;
}

void hd24fs::setprojectsectornum(int i,__uint32 sector) 
{
	getsector_diskinfo();
	Convert::setint32(sector_diskinfo, 
		DRIVEINFO_PROJECTLIST + ((i - 1) * 4),sector);
		
	return;
}

__uint32 hd24fs::deleteproject(__sint32 projid) 
{
	if (projid<1) 
	{
		/* Illegal project id;
                   project IDs are set in base 1. */
		return RESULT_FAIL;
	}

	getsector_diskinfo(); // has list of pointers to project sectors
	__uint32 pcount = Convert::getint32(sector_diskinfo, DRIVEINFO_PROJECTCOUNT);

	if (pcount<=1)
	{
		/* Attempt to delete last project on drive- 
		   not allowed, a drive must always contain
		   at least 1 project */
		return RESULT_FAIL;
	}

	hd24project* projtodel=this->getproject(projid);
	if (projtodel==NULL) {
		return RESULT_FAIL;
	}

	/* If there still all songs in the project, delete them */
	__uint32 currsongcount=projtodel->songcount();
	if (currsongcount>0)
	{
		for (__uint32 j=1; j<=currsongcount;j++) 
		{
			projtodel->deletesong(1); // songs will shift
			projtodel->save();
		}
	}

	/* delete project from project list by shifting left
	   all other projects... */
	if (projid<99)
	{
	        /* When project 99 is deleted no shifting is needed */
		for (__uint32 i=projid;i<99;i++) 
		{
			setprojectsectornum(i,getprojectsectornum(i+1));
		}
	}

	setprojectsectornum(99,0); // ...and clearing the last entry.

	Convert::setint32(sector_diskinfo,DRIVEINFO_PROJECTCOUNT,pcount-1);

	/* Set 'last accessed project' to first in list 
       	   (the project being deleted needs to be accessed 
            prior to deletion so this must always be updated)
        */
	Convert::setint32(sector_diskinfo, DRIVEINFO_LASTPROJECT,getprojectsectornum(1));
#if (HD24FSDEBUG==1)
	cout << "save project." << endl;
#endif

	savedriveinfo();
	delete projtodel;
	return RESULT_SUCCESS;
}

void hd24fs::write_enable()
{
	this->writeprotected=false;
}

void hd24fs::write_disable()
{
	this->writeprotected=true;
}