aboutsummaryrefslogtreecommitdiff
path: root/src/lib/hd24song.cpp
blob: ac1db7799e82171157769f8e04479d877ecf9ba9 (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
#include <config.h>
#include "hd24fs.h"
#include "convertlib.h"
#include "memutils.h"
#define FRAMESPERSEC 30 /* 30 or 100; 30=default for HD24 (=SMPTE rate) */
#define SONGDEBUG	0
#if (SONGDEBUG==1)
#define MEMLEAKMULT 10000
#else
#define MEMLEAKMULT 1
#endif
#define CACHEBUFFERS	30		/* enough for 25 locate points+some lookahead */
#define NOTHINGTOQUEUE			0xFFFFFFFF 
#define CACHEBLOCK_UNUSED		0xFFFFFFFF /* a song can never have this number of blocks
						      because this is the max no. of samples in a song
						      and a block consists of multiple samples */
#define SONGINFO_AUDIOBLOCKS		0x00
#define SONGINFO_SECSAMPLESWITCH	0x8 /* *512=samples before switch to next track */
#define SONGINFO_SECBYTESWITCH		0xC /* *512=bytes before switch to next track */
#define SONGINFO_SONGNAME_8		0x28
#define SONGINFO_CHANNELS		0x31
#define SONGINFO_SAMPLERATE		0x34
#define SONGINFO_BITDEPTH		0x37
#define SONGINFO_SONGLENGTH_IN_SAMPLES	0x38
#define SONGINFO_WRITEPROTECTED		0x3c
#define	SONGINFO_LOCATEPOINTLIST	0xb8
#define LOCATEENTRY_LENGTH		12
#define SONGINFO_SONGNAME 		0x3b8
#define SONGINFO_ALLOCATIONLIST		0x400
#define ALLOCINFO_ENTRYLEN	8
#define ALLOCINFO_SECTORNUM		0x00
#define ALLOCINFO_AUDIOBLOCKSINBLOCK	0x04
#define ALLOC_ENTRIES_PER_SONG	(ALLOC_SECTORS_PER_SONG*(512/ALLOCINFO_ENTRYLEN))
#define LOCATE_TIMECODE		0
#define LOCATE_NAME		4
/*	   Quick calculation: A song is max 2^32 samples * 3 bytes *24 tracks
	   = 309 237 645 312 bytes
	   1 block=0x480h sectors = 589 824 bytes
	   So the max number of blocks in a song = (309237645312 / 589824) blocks = 524288 blocks
*/
#define MAX_BLOCKS_IN_SONG 524288
const int hd24song::LOCATEPOS_SONGSTART	=0;
const int hd24song::LOCATEPOS_LOOPSTART	=1;
const int hd24song::LOCATEPOS_LOOPEND	=2;
const int hd24song::LOCATEPOS_PUNCHIN	=21;
const int hd24song::LOCATEPOS_PUNCHOUT	=22;
const int hd24song::LOCATEPOS_EDITIN	=23;
const int hd24song::LOCATEPOS_EDITOUT	=24;
const int hd24song::LOCATEPOS_LAST	=24;
const int hd24song::READMODE_COPY       =0;
const int hd24song::READMODE_REALTIME   =1;
const int hd24song::WRITEMODE_COPY      =2;
const int hd24song::WRITEMODE_REALTIME  =3;
void hd24song::loadblockintocache(__uint32 blocktoqueue) 
{
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	
	for (int i=LOCATEPOS_LAST;i<CACHEBUFFERS;i++) {
		if (cachebuf_blocknum[i]==blocktoqueue) {
			return; // already in cache.
		}
	}
//	cout << "Caching block " << blocktoqueue << endl;
	cachebuf_blocknum[currcachebufnum]=blocktoqueue;

////////////////////// TODO: THIS BLOCK OF CODE CAN BE REPLACED BY GETFIRSTBLOCKSECTOR
	__uint32 rtallocentrynum=0;		// reset cursor to start of song
	__uint32 rtallocstartblock=0; 	// blocknum of first block in current allocation entry
	__uint32 rtallocstartsector=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*rtallocentrynum)+ALLOCINFO_SECTORNUM);
	__uint32 rtallocaudioblocks=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*rtallocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);
	__uint32 blocknum=blocktoqueue;
	
	while ((blocknum-rtallocstartblock) >= rtallocaudioblocks) {
		rtallocentrynum++;			// reset cursor to start of song
		if (rtallocentrynum>=ALLOC_ENTRIES_PER_SONG ) break;
		rtallocstartblock+=rtallocaudioblocks; 	// blocknum of first block in current allocation entry
		rtallocstartsector=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*rtallocentrynum)+ALLOCINFO_SECTORNUM);
		rtallocaudioblocks=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*rtallocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);

	}
///////////////////////////////////////////////////
//	cout << "allocentrynum=" << rtallocentrynum << endl;
	parentfs->readsectors(parentfs->devhd24,
		rtallocstartsector+((blocknum-rtallocstartblock)*blocksize_in_sectors),
		cachebuf_ptr[currcachebufnum],blocksize_in_sectors); // raw read

//	cachebuf_ptr[currcachebufnum]=NULL; // TODO: READ SECTORS!!!
	
	currcachebufnum++;
	if (currcachebufnum>=CACHEBUFFERS)
	{
		currcachebufnum=LOCATEPOS_LAST+1;
	}
	return;
}


void hd24song::bufferpoll() {
	// A process can call this procedure to tell the song
	// object to check the cache request queue for 	blocks
	// to cache.
	if (currentreadmode==READMODE_COPY) return;
	if (polling==1) 
	{ 
		// Previous poll is still in progress.
		// This is not a proper semaphore system but will
		// help relief processing weight should the system
		// get overloaded. Normally bufferpoll shouldn't be 
		// called much more than around 20 times per second,
		// so the chance two polls interfere with one another
                // is minimal.
		return; 
	}
	polling=1;	// semaphore
	if (blocktoqueue!=NOTHINGTOQUEUE) 
	{
//		cout << "queue request for " <<blocktoqueue << endl;
		loadblockintocache(blocktoqueue);
		blocktoqueue=NOTHINGTOQUEUE;
	}
	polling=0;	// poll done
}

__uint32 hd24song::locatepointcount() {
	return LOCATEPOS_LAST+1;
}

__uint32 hd24song::getlocatepos(int locatepoint)
{
	if (locatepoint<0) locatepoint=0;
	if (locatepoint>LOCATEPOS_LAST) return songlength_in_samples();
	long entryoffset=SONGINFO_LOCATEPOINTLIST+(locatepoint*LOCATEENTRY_LENGTH);
	return Convert::getint32(buffer,entryoffset+LOCATE_TIMECODE);
}

string* hd24song::getlocatename(int locatepoint)
{
	if (locatepoint<0) locatepoint=0;
	if (locatepoint>LOCATEPOS_LAST) {
		string* newstr=new string("END");
		return newstr;
	}
	long entryoffset=SONGINFO_LOCATEPOINTLIST+(locatepoint*LOCATEENTRY_LENGTH);
	return Convert::readstring(buffer,entryoffset+LOCATE_NAME,8);
}


void hd24song::setlocatename(int locatepoint,string newname)
{
	
	if (locatepoint<0) locatepoint=0;
	if (locatepoint>LOCATEPOS_LAST) return;
	while (newname.length()<8) {
		newname+=" ";
	}
	long entryoffset=SONGINFO_LOCATEPOINTLIST+(locatepoint*LOCATEENTRY_LENGTH);
	for (__uint32 i=0;i<8;i++) {
		buffer[entryoffset+LOCATE_NAME+i]=newname.c_str()[i];
	}
	return;
}
void hd24song::silenceaudioblocks(__uint32 allocsector,__uint32 numblocks)
{
	/* Given a sector number and a block count, silence the 
           given number of audio blocks on the drive starting
           from the given sector number.
           This function has 2 modes- one working with a 1-sector
	   stack-allocated block (slow), the other working with
           a heap-allocated cluster (fast but memory intensive).
           The heap method may need up to a few (2.3 or so) megabytes of RAM.
	   If heap allocation fails, the slow method is used.
	*/
	unsigned char onesector[512];
	memset(onesector,0,512);

	__uint32 sectorstoclear=parentfs->getblocksizeinsectors();
	sectorstoclear*=numblocks;
	unsigned char* clearblock=(unsigned char*)memutils::mymalloc("silenceaudioblocks",sectorstoclear*512,1);
	if (clearblock==NULL) 
	{
		// Alloc failed, use low-memory use version
		for (__uint32 i=0;i<sectorstoclear;i++) 
		{
			parentfs->writesectors(parentfs->devhd24,
			allocsector+i,
			onesector,
			1);
		}
	}
	else 
	{
		memset(clearblock,0,512*sectorstoclear);
		parentfs->writesectors(parentfs->devhd24,
		allocsector,
		clearblock,
		sectorstoclear);
		memutils::myfree("silenceaudioblocks",clearblock);
	}
	return;
}

bool hd24song::setallocinfo(bool silencenew)
{
	return setallocinfo(silencenew,NULL,NULL,NULL);
}

__uint32 hd24song::requiredaudioblocks(__uint32 songlen)
{
	/* Figure out how many audio blocks we would expect 
	   the song to have based on the songlength in samples. */
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=physical_channels();
	__uint32 tracksamples_per_block=0;
	if (tracks_per_song>0) {
		tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;
	}
	
	__uint32 remainder=songlen%tracksamples_per_block;
	__uint32 blocks_expected=(songlen-remainder)/tracksamples_per_block;
	if (remainder!=0) {
		blocks_expected++;
	}
        return blocks_expected;
}

bool hd24song::allocatenewblocks(__uint32 blockstoalloc,bool silencenew,char* message,int* cancel,int (*checkfunc)())
{
	/* Allocate space in the real drive usage table.
           Mind that we've been asked to allocate a certain
           number of blocks, although in reality we are not
           allocating blocks but clusters of blocks. */
#if (SONGDEBUG == 1)
	cout << "Total blocks to alloc=" << blockstoalloc << endl;
#endif
	__uint32 totblockstoalloc=blockstoalloc;
	__uint32 allocsector=0;
	__uint32 blockspercluster=parentfs->getblockspercluster();
	cancel=cancel;
	while (blockstoalloc>0)
	{
		__uint32 pct=(__uint32)((100*(totblockstoalloc-blockstoalloc))/totblockstoalloc);
		if (message!=NULL) {
			sprintf(message,
				"Lengthening song... allocating block %ld of %ld, %ld%% done",
				(long)(totblockstoalloc-blockstoalloc),
				(long)totblockstoalloc,
				(long)pct
			);
		}
		if (checkfunc!=NULL)
		{
			checkfunc();
		}
		allocsector=getnextfreesector(allocsector);

#if (SONGDEBUG == 1)
		cout << "Allocsector=" << allocsector << endl;
		cout << "Blockstoalloc=" << blockstoalloc << endl;
#endif
		if (allocsector==0) {
#if (SONGDEBUG == 1)
	cout << "Ran out of space with " << blockstoalloc 
             <<" left to alloc " << endl;
#endif
			
			return false;
		}
		if (silencenew)
		{
			// overwrite cluster with silence.
#if (SONGDEBUG == 1)
			cout << "Overwriting cluster with silence." << endl;
#endif
			this->silenceaudioblocks(allocsector,blockspercluster);
		}
		__uint32 alloccluster=parentfs->sector2cluster(allocsector);
#if (SONGDEBUG == 1)
		cout << "Alloccluster=" << alloccluster << endl;
#endif
		parentfs->enablebit(alloccluster,parentfs->sectors_driveusage);
                if (blockstoalloc>=blockspercluster)
                {
			blockstoalloc-=blockspercluster;	
                } 
		else 
		{
			blockstoalloc=0;
		}
	}
	return true;
}

bool hd24song::setallocinfo(bool silencenew,char* message,int* cancel,int (*checkfunc)())
{
	/* This function is intended for recovering live recordings
	   and lengthening songs. To use it, set a new song length
           first, then call this function- it will add the required
           number of blocks to the song.

	   Boolean 'silencenew' indicates if newly allocated space
           should be overwritten with silence.

           For initializing songs to nonzero length, you will want
           to set this to TRUE.

           For recovering live recordings you will want to set it
           to FALSE.

           For realtime recording, it is set to FALSE for efficiency
           reasons, as the recording algorithm itself will overwrite
           newly allocated space with audio (and silence as needed).
 
	   Savemessage allows giving textual feedback to the user 
           and the int pointed to by cancel will be set to 1 by the 
           GUI if the user interrupts the process. 
           In case of recovering a song, after setting the length of
           a crashed song to the estimated duration, we want to try 
           to find back the audio.

           It is reasonable that this previously recorded audio can be
           found by simply allocating as many unused clusters to the
           song as needed to reach the desired length; because those
           same clusters would have been allocated to the song after
           pressing 'stop'.

           This function attempts to perform this allocation (which
           should also allow people to perform headerless 
           live recoveries).

	   The way this will work is:
 	   -- find out how many audio blocks are allocated to the song;
           -- find out how many we think there *should* be allocated;
           -- then, allocate those blocks (in a copy of the usage table);
           -- finally, append the newly allocated blocks to the song.
           -- the last can be done by subtracting the old usage table
              from the new one and calling appendorphanclusters.

	   FIXME: operation is not correct when running out of drive space.
	   TODO: we count blocks to allocate but in reality clusters are
                 being reserved. Shouldn't we work cluster based all the
                 way?
        */

	__uint32 blocksinalloctable=audioblocks_in_alloctable();
	__uint32 blocks_expected=requiredaudioblocks(songlength_in_samples());


#if (SONGDEBUG == 1)
	cout << "Actual   blocks allocated for song:" << blocksinalloctable << endl;
	cout << "Expected blocks allocated for song:" << blocks_expected << endl;
#endif
	if (blocksinalloctable==blocks_expected) 
	{
		// right amount of space is already allocated.
		return true;
	}

	if (blocksinalloctable>blocks_expected) 
	{
		// looks like too much space is allocated,
		// but setallocinfo() won't support song shrinking
		// for now.
		return false;
	}

	/* Not enough space is allocated-- allocate as much extra as needed. */
#if (SONGDEBUG == 1)
	cout << "Allocating space for song. " <<endl;
#endif
	__uint32 blockstoalloc=blocks_expected-blocksinalloctable;

	unsigned char* copyusagetable=parentfs->getcopyofusagetable();
	if (copyusagetable==NULL) 
	{
		/* Cannot get usage table (out of memory?) */
		return false;
	}

	bool tryallocnew=this->allocatenewblocks(blockstoalloc,silencenew,message,cancel,checkfunc);
	if (tryallocnew==false)
	{
		/* Cannot allocate new blocks (out of drive space?) */
		memutils::myfree("copyusagetable",copyusagetable);
		return false;
	}

	/* Cluster allocation succeeded. 
           To find out which clusters have been allocated,
           XOR the previous copy of the usage table over it.
           This will result in a list of newly allocated 
           (orphan) clusters still to be appended to the song.
        */
	for (__uint32 i=0;i<(512*15);i++) 
	{
		copyusagetable[i]=(copyusagetable[i])
                                 ^(parentfs->sectors_driveusage[i]);
	}
	
#if (SONGDEBUG == 1)
	cout << "Alloc action successful- append orphan clusters now." << endl;
#endif
	// call appendorphanclusters
	if (message!=NULL) 
	{
		sprintf(message,"Adding allocated space to song...");
		if (checkfunc!=NULL)
		{
			checkfunc();
		}
	}
	bool songresize;
	if (silencenew) {
		songresize=false;
	}
	else 
	{
		songresize=true;
	}
	appendorphanclusters(copyusagetable,songresize);
	memutils::myfree("copyusagetable",copyusagetable);
	// save for either song or drive usage table is not
	// to be called here- it would violate the concept
	// of safe, read-only recovery.	
	return true;
}

void hd24song::appendorphanclusters(unsigned char* usagebuffer,bool allowsongresize)
{
	__uint32 clusters=parentfs->clustercount();
	__uint32 currpos=0;
	__uint32 curralloctableentry=used_alloctable_entries();
#if (SONGDEBUG == 1)
	cout << "Appending orphan clusters to song. Used alloctable entries=" << curralloctableentry 
	<< "clusters=" << clusters
	<< endl;
#endif

	while (currpos<clusters) {
		__uint32 blockstart=currpos;
		while (parentfs->isfreecluster(blockstart,usagebuffer) && (blockstart<clusters)) {
			blockstart++;
		}
#if (SONGDEBUG == 1)
		cout << "Block starts at cluster " <<blockstart << endl;
#endif
		if (blockstart==clusters) {
			break;
		}

		// blockstart now points to a nonfree cluster
		__uint32 blockend=blockstart;
		while (!parentfs->isfreecluster(blockend,usagebuffer) && (blockend<clusters)) {
			blockend++;
		}
		// blockend now points to a free cluster
		currpos=blockend;
		__uint32 blocklen=blockend-blockstart;

		__uint32 entrystartsector=(unsigned int) (parentfs->cluster2sector(blockstart));
		__uint32 entrynumblocks=(unsigned int)( parentfs->getblockspercluster()*blocklen );
		Convert::setint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_SECTORNUM
			+(ALLOCINFO_ENTRYLEN*curralloctableentry),entrystartsector);

		Convert::setint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_AUDIOBLOCKSINBLOCK
			+(ALLOCINFO_ENTRYLEN*curralloctableentry),entrynumblocks);
		curralloctableentry++;
#if (SONGDEBUG == 1)
		printf("%x %x\n",(unsigned int)parentfs->cluster2sector(blockstart),(unsigned int)( parentfs->getblockspercluster()*blocklen ));
#endif
	}
	/* the operation may have resulted in the song getting	
	   longer. This is due to the fact that while recording,
           'stop' may be pressed before all audio blocks of the
           cluster have been used.
           Also, of course, there may be more orphaned clusters
           around than belong to the song- for whatever reason.
        */

	__uint32 blocksinalloctable=audioblocks_in_alloctable();
	
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=physical_channels();
	__uint32 tracksamples_per_block=0;
	if (tracks_per_song>0) {
		tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;
	}
	__uint32 newsonglen=tracksamples_per_block*blocksinalloctable;
	Convert::setint32(buffer,SONGINFO_AUDIOBLOCKS,blocksinalloctable);

	/* The following directly sets the songlength in the song buffer
	   rather than via songlength_in_samples(val) to prevent
	   testing whether more space needs to be allocated-
           which is not needed as space has just been allocated. 
           (Also, the below number may be less accurate than the
           number some user might specify via songlength_in_samples(val)).
        */
	if (allowsongresize)
	{
        	Convert::setint32(buffer,SONGINFO_SONGLENGTH_IN_SAMPLES,newsonglen);
	}
       	return; 
}

void hd24song::setblockcursor(__uint32 blocknum) 
{
	allocentrynum=0;	// reset cursor to start of song
	allocstartblock=0; 	// blocknum of first block in current allocation entry
	allocstartsector=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_SECTORNUM);
	allocaudioblocks=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);
	// cout << " allocaudioblocks=" << allocaudioblocks << endl;	
	while ((blocknum-allocstartblock) >= allocaudioblocks) {
		allocentrynum++;			// reset cursor to start of song
		allocstartblock+=allocaudioblocks; 	// blocknum of first block in current allocation entry
		allocstartsector=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_SECTORNUM);
		allocaudioblocks=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);
	}
	return;
}

void hd24song::unmark_used_clusters(unsigned char* sectors_inuse)
{
	/*
 	 * Given an image of used clusters, this function
 	 * will alter that image to unmark the clusters
 	 * in use by this song.
 	 * Under normal circumstances, this is used to
 	 * delete songs. 
 	 * However, it is also useful to search for orphan 
 	 * clusters (by unmarking all clusters in use by 
 	 * all songs- the remaining clusters then must be 
 	 * orphan clusters)
 	 */
#if (SONGDEBUG == 1)
	cout << "unmark used clusters." << endl;
#endif
	__uint32 allocentries=used_alloctable_entries();

	if (allocentries==0) {
#if (SONGDEBUG == 1)
		cout << "Song claims no used allocation entries." << endl;
#endif
		return;
	}

	__uint32 blockspercluster=parentfs->getblockspercluster();

	for (__uint32 i=0; i<allocentries; i++) 
	{
		__uint32 entrystartsector=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_SECTORNUM
			+(ALLOCINFO_ENTRYLEN*i));

		__uint32 entrynumblocks=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_AUDIOBLOCKSINBLOCK
			+(ALLOCINFO_ENTRYLEN*i));


		__uint32 entrystartcluster=parentfs->sector2cluster(entrystartsector);
#if (SONGDEBUG == 1)
		cout << "startsector=" <<entrystartsector << " blocks=" << entrynumblocks <<" clust=" << entrystartcluster << endl;
#endif

		__uint32 entrynumclusters=(entrynumblocks-(entrynumblocks%blockspercluster))/blockspercluster;
		if ((entrynumblocks%blockspercluster)!=0) 
		{
			entrynumclusters++;
		}
#if (SONGDEBUG == 1)
			cout << "buffer=" << buffer << endl;
#endif
		if (entrynumclusters==0) 
		{
#if (SONGDEBUG == 1)
			cout << "nothing to free here." << endl;
#endif

		}
		for (__uint32 j=0;j<entrynumclusters;j++) {
			__uint32 clust2free=j+entrystartcluster;
			parentfs->freecluster(clust2free,sectors_inuse);
#if (SONGDEBUG == 1)
			cout << clust2free << " ";
#endif
		}
#if (SONGDEBUG == 1)
		cout << endl;
#endif
	}
}

__uint32 hd24song::currentlocation()
{
	return songcursor;
}
void hd24song::currentlocation(__uint32 offset)
{
	golocatepos(offset);
}

__uint32 hd24song::golocatepos(__uint32 offset)
{
	/* Offset indicates next sample that will be 
	   played back (or recorded). A song of 1 sample long
	   can have the cursor set at offset 0 or offset 1;
           offset 1 is then beyond the end of the song, which is
	   meaningful for recording but not for playback. */

	__uint32 songlen=songlength_in_samples();

	if (offset>songlen) {
		offset=songlen;
		//return offset;
	}

	songcursor=offset;
	evenodd=0;

	__uint32 samplenumber=songcursor;	
#if (SONGDEBUG == 1)
//	cout << "songcursor=" << songcursor << endl; 
#endif
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=physical_channels();
	__uint32 tracksamples_per_block=0;
	if (tracks_per_song>0) {
		tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;
	}
	__uint32 blocknum=0;
	if (tracksamples_per_block>0) {
		blocknum=(samplenumber/(tracksamples_per_block));
	}

#if (SONGDEBUG == 1)
//	cout << "still going strong" << endl; 
#endif

	setblockcursor(blocknum);	

	return songcursor;
}

__uint32 hd24song::setlocatepos(int locatepoint,__uint32 offset)
{
	/** Sets the value of a locate point to the given offset.
            Parameters: 
            locatepoint
		The 0-based locate point identifier
            offset
		The new offset (in samples*) for the locate point.
 		* In high samplerate songs (88k2, 96k), the offset is given as
                number of sample pairs, because audio data is interlaced 
            	across 2 physical tracks.
        */

	if (locatepoint<0) 
        {
		locatepoint=0;
	}

	if (locatepoint>LOCATEPOS_LAST) 
	{
		return 0;
	}

	long entryoffset=SONGINFO_LOCATEPOINTLIST
                        +(locatepoint*LOCATEENTRY_LENGTH);

	buffer[entryoffset+LOCATE_TIMECODE+3]=offset%256;
	offset=offset>>8;
	buffer[entryoffset+LOCATE_TIMECODE+2]=offset%256;
	offset=offset>>8;
	buffer[entryoffset+LOCATE_TIMECODE+1]=offset%256;
	offset=offset>>8;
	buffer[entryoffset+LOCATE_TIMECODE+0]=offset%256;
	return getlocatepos(locatepoint);
}

hd24song::hd24song(hd24project* p_parent,__uint32 p_songid) 
{
#if (SONGDEBUG == 1)
	cout << "CONSTRUCT hd24song " << p_songid << endl;
#endif
	currentreadmode=READMODE_COPY;
	blocktoqueue=NOTHINGTOQUEUE;
	polling=0;
	evenodd=0;
	audiobuffer=NULL;
	scratchbook=NULL;
	buffer=NULL;
	framespersec=FRAMESPERSEC;
	lastallocentrynum=0; 	
	busyrecording=false;
	mysongid=p_songid;
	rehearsemode=false;
	lengthened=false;
	lastavailablecacheblock=0xFFFFFFFF;
	currcachebufnum=LOCATEPOS_LAST+1;
	buffer=(unsigned char*)memutils::mymalloc("hd24song-buffer",16384,1);
	parentfs=p_parent->parentfs;
	parentproject=p_parent;
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;

	for (__uint32 tracknum=1;tracknum<=24;tracknum++) 
	{
		track_armed[tracknum-1]=false;
	}

	// 'read enabled' is used in copy mode to reduce the amount of
	// secors that need to be read from disk.	
	for (__uint32 tracknum=1;tracknum<=24;tracknum++) 
	{
		track_readenabled[tracknum-1]=true; // by default all are read enabled.
	}

#if (SONGDEBUG == 1)
	cout << "2" << endl;
#endif
	audiobuffer=(unsigned char *)memutils::mymalloc("hd24song-audiobuffer",blocksize_in_bytes+SECTORSIZE,1);
	scratchbook=(unsigned char *)memutils::mymalloc("hd24song-scratchbook",blocksize_in_bytes+SECTORSIZE,1);

	if (audiobuffer==NULL) {
#if (SONGDEBUG ==1)
		cout << "could not allocate audio buffer" << endl;
#endif
	}
	
	// Set up cache buffers for realtime access
	// first, dynamically create pointer array
	cachebuf_blocknum=(__uint32*)memutils::mymalloc("hd24song-cachebuf",sizeof(__uint32)*CACHEBUFFERS,1);
	cachebuf_ptr=(unsigned char**)memutils::mymalloc("hd24song-cachebufptr",sizeof (unsigned char *)*CACHEBUFFERS,1);
	// then, allocate blocks and point array to it.
	int i;
	
	for (i=0;i<CACHEBUFFERS;i++)
	{
		cachebuf_ptr[i]=NULL;
	}

	for (i=0;i<CACHEBUFFERS;i++)
	{
		cachebuf_blocknum[i]=CACHEBLOCK_UNUSED;
		cachebuf_ptr[i]=(unsigned char*)memutils::mymalloc("hd24song-cachebufptr[i]",blocksize_in_bytes,1);
	}

	__uint32 songsector=parentproject->getsongsectornum(mysongid);
#if (SONGDEBUG ==1) 
	cout << "Reading # song sectors= " << TOTAL_SECTORS_PER_SONG 
	<< "from sec " << songsector << endl;
#endif	
	parentfs->readsectors(parentfs->devhd24,
			songsector,
			buffer,TOTAL_SECTORS_PER_SONG);
	parentfs->fstfix(buffer,TOTAL_SECTORS_PER_SONG*512);
	//ncout << "sectors read="<<dummy<<endl;
	
#if (SONGDEBUG ==1) 
	cout << "alloc mem for blocksectors" << endl;	
#endif

	blocksector=(__uint32*)memutils::mymalloc("blocksector",600000,sizeof(__uint32));
#if (SONGDEBUG ==1) 
	cout << "Blocksector=" <<blocksector << endl;	
	cout << "clear blocksectors" << endl;	
#endif
	for (int i=0; i<600000;i++) { 
		blocksector[i]=0; 
	}
	// how many blocks in this song?
#if (SONGDEBUG == 1)
	cout << "cleared blocksectors" << endl;	

	cout << "create song" << mysongid << endl;
	cout << "blocksize in bytes=" << blocksize_in_bytes << endl;
	cout << "bitdepth in bytes=" << bitdepth()/8 << endl;
	cout << "phys_channels=" << physical_channels() << endl;
#endif
	if (physical_channels() >0) 
	{
		__uint32 blocksize_in_samples=blocksize_in_bytes / (physical_channels()* (bitdepth()/8));
		__uint32 number_of_blocks=(__uint32) floor ( songlength_in_samples() / blocksize_in_samples  );
#if (SONGDEBUG == 1)
		cout << "songlen in sam=" <<  songlength_in_samples() << endl;
#endif
		if (	( songlength_in_samples() % blocksize_in_samples ) !=0 ) 
		{
			number_of_blocks++;
		}

	
#if (SONGDEBUG == 1)
		cout << " blocksize in sams = " << blocksize_in_samples;
	       	cout << "=" << number_of_blocks << "blocks " << endl;

		cout << "memoize alloc info for " << number_of_blocks << "blocks." << endl;
#endif
		memoizeblocksectors(number_of_blocks);
	}
	
	divider=0;
	lastreadblock=0; 
	mustreadblock=1; // next time a sample is requested, we must read from disk
	//cout << "golocatepos" << endl;
	golocatepos(0);
	//cout << "locate done" << endl;
}

__uint32 hd24song::songid()
{
	return this->mysongid;
}

bool hd24song::has_unexpected_end()
{
	// Check if this song has an 'unexpected end of song' error
	// (in header mode, this always returns false)
	if (this->parentfs->headersectors!=0) 
	{
		return false;
	}
	// find out how many audioblocks are claimed to be allocated in the
	// song allocation info table

	__uint32 blocksinalloctable=audioblocks_in_alloctable();

	if ( blocksinalloctable < Convert::getint32(buffer,SONGINFO_AUDIOBLOCKS) ) 
	{
		// the song itself claims it should have more audioblocks
		return true;
	}
	// Over here we could also verify the expected number of blocks
	// against the given song length in samples.
	return false;
}

bool hd24song::is_fixable_unexpected_end()
{
	/** Checks if this song has a FIXABLE 'unexpected end of song' error */
	__uint32 blocksinalloctable=audioblocks_in_alloctable();
#if (SONGDEBUG == 1)
		cout << "Blocks in alloctable=" << blocksinalloctable << endl;
#endif
        __uint32 songblockcount=Convert::getint32(buffer,SONGINFO_AUDIOBLOCKS);
	if (songblockcount>MAX_BLOCKS_IN_SONG)
        {
		/* Safety feature: corruption detected, 
                   block count of song is greater than theoretical maximum. */
                songblockcount=MAX_BLOCKS_IN_SONG;
        }

        /* Values in songblockcount and blocksinalloctable should be equal 
           unless the song is corrupt. If the latter value lower,
           there is an 'unexpected end of song' error. */

	if (!( blocksinalloctable < songblockcount ))
	{
		// No unexpected end of song error, nothing to fix
		return false;
	}

        /* There is an unexpected end of song error. But is it one of
           the type we know how to automatically fix? */

	if (used_alloctable_entries() == (512/ALLOCINFO_ENTRYLEN) ) {
		/* Yes, it is. We have exactly 1 sector of allocated data and
		   the rest is zero data, due to a known (presumed) bug in 
                   the HD24 recorder. */
		return true;
	}
	
	/* No, it isn't. Then assume we cannot fix it. */
	return false;
}

__uint32 hd24song::used_alloctable_entries()
{
	/** Counts how many entries in the song allocation table
            are in use. */
	__uint32 MAXALLOCENTRIES=((512/ALLOCINFO_ENTRYLEN)*5)-1;

	for (__uint32 i=0;i<MAXALLOCENTRIES;i++)
	{
		__uint32 entrystartsector=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_SECTORNUM
			+(ALLOCINFO_ENTRYLEN*i));
		if (entrystartsector==0) {
			return i;
		}
	}
	return MAXALLOCENTRIES;
}

__uint32 hd24song::audioblocks_in_alloctable()
{	
	/** Finds out how many audio blocks are claimed in
	    the allocation table of the song. */
	__uint32 checkentries=used_alloctable_entries();
	if (checkentries==0) {
		return 0;
	}
	__uint32 totblocks=0;

	for (__uint32 i=0; i<checkentries; i++) 
	{
		__uint32 entrynumblocks=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_AUDIOBLOCKSINBLOCK
			+(ALLOCINFO_ENTRYLEN*i));
		totblocks+=entrynumblocks;

	        if (totblocks>MAX_BLOCKS_IN_SONG) 
        	{
	            /* Safety net: Corruption detected, song claims to use 
                       more blocks than the theoretical possible maximum. */
                    return MAX_BLOCKS_IN_SONG;
                }
	}

	return totblocks;
}

hd24song::~hd24song() 
{
#if (SONGDEBUG == 1)
	cout << "DESTRUCT hd24song " << mysongid << endl;
#endif
	if (buffer!=NULL) 
	{
		memutils::myfree("buffer",buffer);
		buffer=NULL;
	}
	if (scratchbook != NULL)
	{
		memutils::myfree("scratchbook",scratchbook);
		scratchbook=NULL;
	}
	if (audiobuffer != NULL)
	{
		memutils::myfree("audiobuffer",audiobuffer);
		audiobuffer=NULL;
	}
	if (blocksector != NULL) 
	{
		memutils::myfree("blocksector",blocksector);
		blocksector=NULL;
	}
	int i;
	
	// clear cache
	for (i=0;i<CACHEBUFFERS;i++) 
	{
		if (cachebuf_ptr[i]!=NULL) {
			memutils::myfree("cachebuf_ptr[i]",cachebuf_ptr[i] );	
		}
	}
	if (cachebuf_ptr!=NULL)
	{
		memutils::myfree("cachebuf_ptr",cachebuf_ptr);
	}
	if (cachebuf_blocknum!=NULL) 
	{
		memutils::myfree("cachebuf_blocknum",cachebuf_blocknum);
	}
//	cout << "del song " << mysongid <<  endl;
}

void hd24song::queuecacheblock(__uint32 blocknum) 
{
	// Only process request if the block is neither cached nor queued yeta
	// This function is only called if a block is not cached.
	// In addition, as playback progresses, the more blocks are queued,
	// the less importance the oldest blocks have.
	// For this reason, a circular queue would make sense-- if too many blocks
	// get queued, the last one requested can be ignored.
	// The queue needn't be very big; a shortcut is to use a queue of
	// just 1 element long. This should still work OK because a block
	// queue request may be issued over and over again until it is cached.
	if (blocknum!=blocktoqueue) 
	{
		// block not yet queued
//		cout << "Processing request to queue block " << blocknum  << " for caching " << endl;
	}	
	blocktoqueue=blocknum;
	return;
}

string* hd24song::songname(hd24fs* parentfs, unsigned char* songbuf)
{
	string* ver=parentfs->version();
	if (*ver == "1.00") {
		// version 1.0 filesystem.
		delete ver;
		string* tmp=new string("");
		string* dummy=Convert::readstring(songbuf,SONGINFO_SONGNAME_8,8);
	
		*tmp+=*dummy;
		delete dummy;
		if (tmp->length()==8) {
			dummy=Convert::readstring(songbuf,SONGINFO_SONGNAME_8+10,2);
		        *tmp+=*dummy;
			delete dummy;
		}
		return tmp;
	}
	delete ver;
	string* tmp=Convert::readstring(songbuf,SONGINFO_SONGNAME,64);
	return tmp;
}

string* hd24song::songname() 
{
	return songname(this->parentfs,buffer);
}

void hd24song::songname(string newname)
{
	songname(buffer,newname);
}

void hd24song::songname(unsigned char* songbuf,string newname)
{
	hd24fs::setname(songbuf,newname,SONGINFO_SONGNAME_8,SONGINFO_SONGNAME);
	return;
}

bool hd24song::iswriteprotected() 
{
	__uint32 writeprot=(Convert::getint32(buffer,SONGINFO_WRITEPROTECTED));
	writeprot&=0x04000000;
	if (writeprot==0) return false;
	return true;
}

void hd24song::setwriteprotected(bool prot)
{
	__uint32 writeprot=(Convert::getint32(buffer,SONGINFO_WRITEPROTECTED));
	writeprot&=0xFBFFFFFF;
	
	if (prot) {
		writeprot|=0x04000000;
	}
	Convert::setint32(buffer,SONGINFO_WRITEPROTECTED,writeprot);
	return;
}

void hd24song::physical_channels(unsigned char* songbuf,__uint32 newchannelcount)
{
	if (newchannelcount>24) newchannelcount=24;
	songbuf[SONGINFO_CHANNELS]=(unsigned char)(newchannelcount&0xFF);
}

void hd24song::physical_channels(__uint32 newchannelcount)
{
	physical_channels(buffer,newchannelcount);
}

__uint32 hd24song::physical_channels(unsigned char* songbuf)
{
	int channels=Convert::getint32(songbuf,SONGINFO_CHANNELS)>>24;
	channels=(channels & 0x1f);
	if (channels>24) channels=24;
	return channels;
}

__uint32 hd24song::physical_channels() 
{
	return physical_channels(buffer);
}

__uint32 hd24song::logical_channels() 
{
	if (this->samplerate()>=88200) 
	{
		return (physical_channels()>>1);
	} else {
		return (physical_channels());
	}
}

__uint32 hd24song::logical_channels(unsigned char* songbuf) 
{
	if (samplerate(songbuf)>=88200) 
	{
		return (physical_channels(songbuf)>>1);
	} else {
		return (physical_channels(songbuf));
	}
}

void hd24song::logical_channels(unsigned char* songbuf,__uint32 channelcount)
{
	if (samplerate(songbuf)>=88200) {
		physical_channels(songbuf,channelcount*2);
	} else {
		physical_channels(songbuf,channelcount);
        }
}

__uint32 hd24song::samplerate(unsigned char* songbuf) 
{
	__uint32 samrate=Convert::getint32(songbuf,SONGINFO_SAMPLERATE)>>8;
	return samrate;
}

__uint32 hd24song::samplerate() 
{
	return samplerate(buffer);
}

void hd24song::samplerate(unsigned char* songbuf,__uint32 newrate) 
{
	__uint32 samrate=(newrate<<8);
	__uint32 bd=((unsigned char)songbuf[SONGINFO_BITDEPTH]);
	samrate|=bd;
	Convert::setint32(songbuf,SONGINFO_SAMPLERATE,samrate);        
}

void hd24song::samplerate(__uint32 newrate) 
{
	samplerate(buffer,newrate);
}


__uint32 hd24song::bitdepth() 
{
	__uint32 depth=(__uint32)((unsigned char)buffer[SONGINFO_BITDEPTH]);
	if ((depth!=24) && (depth !=16) && (depth!=32)) return 24;
	return depth;
}

__uint32 hd24song::songlength_in_samples() 
{
	return (Convert::getint32(buffer,SONGINFO_SONGLENGTH_IN_SAMPLES));
}

__uint32 hd24song::songlength_in_samples(__uint32 newlen,bool silencenew)
{
	return  hd24song::songlength_in_samples(newlen,silencenew,NULL,NULL);
}

__uint32 hd24song::songlength_in_samples(__uint32 newlen,bool silencenew,char* savemessage,int* cancel)
{
	return hd24song::songlength_in_samples(newlen,silencenew,savemessage,cancel,NULL);
}

hd24fs* hd24song::fs()
{
	return this->parentfs;
}

__uint32 hd24song::songlength_in_samples(__uint32 newlen,bool silencenew,char* savemessage,int* cancel,int (*checkfunc)())
{
	/* Sets the length of a song and updates any allocation
	   info as needed.
           The return value of the function is the actual song length
	   set. Return value may differ from newlen if not enough drive
	   space was available or if allocating ran into problems
	   otherwise. */
	if (this==NULL)
	{
#if (SONGDEBUG==1)
	cout << "Song object is NULL! Cannot lengthen song." << endl;
#endif
		return 0;
	}
	__uint32 oldlen=songlength_in_samples();
	if (savemessage!=NULL)
	{
		// clear default save message
		savemessage[0]='\0';
	}
	if (cancel!=NULL)
	{
		*cancel=0;
	}
#if (SONGDEBUG==1)
	cout << "Lengthening song to " << newlen << " samples" << endl;
	if (silencenew) {
		cout << "(And silencing new blocks)" << endl;
	}
#endif
        Convert::setint32(buffer,SONGINFO_SONGLENGTH_IN_SAMPLES,newlen);
	if (newlen==0) {
		Convert::setint32(buffer,SONGINFO_AUDIOBLOCKS,0);
		return 0;
	}

	// the above is required by setallocinfo
	if (setallocinfo(silencenew,savemessage,cancel,checkfunc)) {
		// setting alloc info succeeded
#if (SONGDEBUG==1)
	cout << "Success lengthening song to " << newlen << " samples" << endl;
#endif
		this->lengthened=true;
                memoizeblocksectors(Convert::getint32(buffer,SONGINFO_AUDIOBLOCKS));
		return newlen;
	}
	// setting new length failed- reset song to old length.
#if (SONGDEBUG==1)
	cout << "Failed. Keep at old length of " <<oldlen << endl;
#endif
        Convert::setint32(buffer,SONGINFO_SONGLENGTH_IN_SAMPLES,oldlen);
	return oldlen;
}

__uint32 hd24song::songlength_in_samples(__uint32 newlen)
{
	return songlength_in_samples(newlen,true);
}

string* hd24song::display_cursor() 
{
	return (display_duration(songcursor));	
}
__uint32 hd24song::cursorpos() 
{
	return songcursor;
}


string* hd24song::display_duration(__uint32 offset,__uint32 samrate) 
{
	//cout << "dispdur" << offset << endl;
	if (samrate==0) 
	{
		string* nulldur=Convert::int2str(0,2,"0");
		*nulldur+=":00:00.00";
		return nulldur;	
	}
	//cout <<"disphours "<<offset << endl;
	//cout << "samrateh=" <<samplerate() << endl;
	if (samrate>=88200) { samrate=samrate>>1; }
	__uint32 subsec=display_subseconds(offset,samrate);
	if (samrate>0) {
		subsec=this->framespersec*subsec/samrate;
	}
	string* newstr=	Convert::int2str(display_hours(offset),2,"0");
	*newstr+=":";
	string* mins=Convert::int2str(display_minutes(offset),2,"0");
	*newstr+=*mins;
	delete mins;
        *newstr+=":";
	string* secs=Convert::int2str(display_seconds(offset),2,"0");
	*newstr+=*secs;
	delete secs;
        *newstr+=".";
	string* subsecs=Convert::int2str(subsec,2,"0");
	*newstr+=*subsecs;
	delete subsecs;
	return newstr;
}

string* hd24song::display_duration(__uint32 offset) 
{
	return display_duration(offset,samplerate());
}

string* hd24song::display_duration()
{
	__uint32 songlen=songlength_in_samples();
	return display_duration(songlen);
}

__uint32 hd24song::display_hours() 
{
	__uint32 songlen=songlength_in_samples();
	return display_hours(songlen);
}

__uint32 hd24song::display_hours(__uint32 offset,__uint32 samrate) 
{
	if (samrate==0) 
	{	
		return 0;	
	}
	//cout <<"disphours "<<offset << endl;
	//cout << "samrateh=" <<samplerate() << endl;
	if (samrate>=88200) { samrate=samrate>>1; }
	
        __uint32 totsonglen=offset;
	__uint32 songsubsecs=totsonglen%samrate;
	__uint32 cutsonglen=(totsonglen-songsubsecs);
	__uint32 totsongsecs=(cutsonglen/samrate);
	__uint32 viewsongsecs=totsongsecs%60;
	__uint32 totsongmins=(totsongsecs-viewsongsecs)/60;
	__uint32 viewsongmins=(totsongmins%60);
	__uint32 totsonghours=(totsongmins-viewsongmins)/60;
	return totsonghours;
}

__uint32 hd24song::display_minutes() 
{
	return display_minutes(songlength_in_samples());
}

__uint32 hd24song::display_minutes(__uint32 offset,__uint32 samrate) 
{
	if (samrate==0) 
	{	
		return 0;	
	}
	//cout <<"dispmin "<<offset << endl;
	//cout << "samratem=" <<samplerate() << endl;
	if (samrate>=88200) { samrate=samrate>>1; }
        __uint32 totsonglen=offset;
	__uint32 songsubsecs=totsonglen%samrate;
	__uint32 cutsonglen=(totsonglen-songsubsecs);
	__uint32 totsongsecs=(cutsonglen/samrate);
	__uint32 viewsongsecs=totsongsecs%60;
	__uint32 totsongmins=(totsongsecs-viewsongsecs)/60;
	__uint32 viewsongmins=(totsongmins%60);
	return viewsongmins;
}

__uint32 hd24song::display_seconds() 
{
	return display_seconds(songlength_in_samples());
}

void hd24song::sectorinit(unsigned char* songsector)
{	
	unsigned char emptysong[512] = {
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X10,0X00,0X00,0X00,0X30,0X00,0X00,0X00,
		0X00,0X20,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X67,0X6E,0X6F,0X53,0X6D,0X61,0X4E,0X20,
		0X20,0X65,0X18,0X00,0X18,0X44,0XAC,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X01,0X02,0X00,0X00,0XE4,0X12,0X04,0X30,0XA8,0X10,0X00,0X20,
		0X00,0X00,0X00,0X20,0X01,0X00,0X13,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X41,0X54,0X53,0X20,
		0X20,0X20,0X54,0X52,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X31,0X30,0X6D,0X61,
		0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X32,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,
		0X4E,0X63,0X6F,0X4C,0X33,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,
		0X34,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X35,0X30,0X6D,0X61,
		0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X36,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,
		0X4E,0X63,0X6F,0X4C,0X37,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,
		0X38,0X30,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X39,0X30,0X6D,0X61,
		0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X30,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,
		0X4E,0X63,0X6F,0X4C,0X31,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,
		0X32,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X33,0X31,0X6D,0X61,
		0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X34,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,
		0X4E,0X63,0X6F,0X4C,0X35,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,
		0X36,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X37,0X31,0X6D,0X61,
		0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,0X38,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,
		0X4E,0X63,0X6F,0X4C,0X39,0X31,0X6D,0X61,0X00,0X00,0X00,0X00,0X4E,0X63,0X6F,0X4C,
		0X30,0X32,0X6D,0X61,0X00,0X00,0X00,0X00,0X63,0X6E,0X75,0X50,0X20,0X6E,0X49,0X68,
		0X00,0X00,0X00,0X00,0X63,0X6E,0X75,0X50,0X74,0X75,0X4F,0X68,0X00,0X00,0X00,0X00,
		0X74,0X69,0X64,0X45,0X20,0X6E,0X49,0X20,0X00,0X00,0X00,0X00,0X74,0X69,0X64,0X45,
		0X74,0X75,0X4F,0X20,0X04,0X04,0X00,0X00,0X78,0X00,0X00,0X00,0X00,0X00,0X00,0X00,
		0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00,0X00
	};
	for (int i=0;i<1024;i++) {
		songsector[i]=0; // wipe clean entire buffer
	}
	for (int i=0;i<512;i++) {
		songsector[i]=emptysong[i]; // init with empty song info
	}
	hd24fs::fstfix(songsector,1024); // from native drive format to normal byte ordering
	songname(songsector,"Song Name");
}

__uint32 hd24song::display_seconds(__uint32 offset,__uint32 samrate)
{
	if (samrate==0) 
	{	
		return 0;	
	}
	if (samrate>=88200) { samrate=samrate>>1; }
	__uint32 cutsonglen=offset-display_subseconds(offset,samrate);
	__uint32 totsongsecs=(cutsonglen/samrate);
	__uint32 viewsongsecs=totsongsecs%60;
	return viewsongsecs;
}

__uint32 hd24song::display_subseconds() {
	return display_subseconds(songlength_in_samples());
}

__uint32 hd24song::display_subseconds(__uint32 offset,__uint32 samrate) 
{
	if (samrate==0) 
	{	
		return 0;	
	}
	if (samrate>=88200) { samrate=samrate>>1; }
        __uint32 totsonglen=offset;
	__uint32 songsubsecs=totsonglen%samrate;
	return songsubsecs;
}

__uint32 hd24song::display_hours(__uint32 offset) 
{
	return display_hours(offset,samplerate());
}

__uint32 hd24song::display_minutes(__uint32 offset) 
{
	return display_minutes(offset,samplerate());
}

__uint32 hd24song::display_seconds(__uint32 offset) 
{
	return display_seconds(offset,samplerate());
}

__uint32 hd24song::display_subseconds(__uint32 offset) 
{
	return display_subseconds(offset,samplerate());
}

unsigned char* hd24song::getcachedbuffer(__uint32 blocknum) 
{
	// This will return a pointer to an audio buffer containing
	// the audio of the given blocknum, if available.
	// If not available, it will return a pointer to a silent
	// block and queue the blocknum for caching
	int i;
	bool foundbuf=false;
	unsigned char* bufptr=NULL;

	/* A straight loop isn't the fastest way to find the
	 * correct buffer (a binary tree or hash would perform
	 * better). However the advantage for a total of around
	 * 40 blocks (25 locate points and some lookahead) 
	 * would be rather marginal. */

	bool havenext=false;
	bool haveprev=false;

	for (i=LOCATEPOS_LAST;i<CACHEBUFFERS;i++) 
	{
		if (blocknum>0) {
			if (cachebuf_blocknum[i]==(blocknum-1)) {
				haveprev=true;
				if (havenext && foundbuf) break;
			}
		}
		if (cachebuf_blocknum[i]==(blocknum+1)) {
			havenext=true;
			if (haveprev && foundbuf) break;
		}
		if (cachebuf_blocknum[i]==blocknum) 
		{
			bufptr=cachebuf_ptr[i];
			foundbuf=true;
			if (havenext && haveprev) break;
		}
	}
	if (!(foundbuf)) 
	{
		if (!haveprev) 
		{
			queuecacheblock(blocknum-1);
		}
		if (!havenext) 
		{
			queuecacheblock(blocknum+1);
		}
		queuecacheblock(blocknum);
		return NULL;
	}
	if (!haveprev) 
	{
		queuecacheblock(blocknum-1);
	}
	if (!havenext) 
	{
		queuecacheblock(blocknum+1);
	}
	// Cache buffer was found.
	// If we want we can optimize the cache here.
	// Otherwise, just return the buffer pointer.
	lastavailablecacheblock=blocknum;
	return bufptr;
}

void hd24song::memoizeblocksectors(__uint32 number_of_blocks) 
{
	__uint32 totblocksfound=0;
	__uint32 myallocentrynum=0;

	__uint32 entrystartsector=0;
	__uint32 entrynumblocks=0;

	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();

	while (
		(totblocksfound < number_of_blocks)
		&& (totblocksfound <= MAX_BLOCKS_IN_SONG)
		&& (myallocentrynum<ALLOC_ENTRIES_PER_SONG)
	)
	{

		entrystartsector=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_SECTORNUM
			+(ALLOCINFO_ENTRYLEN*myallocentrynum));
		entrynumblocks=Convert::getint32(buffer,
			SONGINFO_ALLOCATIONLIST+ALLOCINFO_AUDIOBLOCKSINBLOCK
			+(ALLOCINFO_ENTRYLEN*myallocentrynum));
#if (SONGDEBUG == 1)
		cout << "Entry " << myallocentrynum << " start sector=" << entrystartsector ;
		cout << "# blocks in entry=" << entrynumblocks << endl;
#endif

		for (__uint32 filler=0;filler<entrynumblocks;filler++) {
			if (totblocksfound+filler > MAX_BLOCKS_IN_SONG) break;
			blocksector[totblocksfound+filler]=entrystartsector+(blocksize_in_sectors*filler);
		}
		totblocksfound+=entrynumblocks;
		myallocentrynum++;
	}
        lastallocentrynum=myallocentrynum;
#if (SONGDEBUG == 1)
	cout << "Tot blocks found = " << totblocksfound << "/" << number_of_blocks << endl;
#endif
	return	;
}
	
/*	   Quick calculation: 
	   Saving 1 block sectornum=32 bit (4 bytes).
           MAX_BLOCKS_IN_SONG=524288, so the maximum number of bytes needed to 
           memoize all song allocation info=524288*4=2097152 bytes (~2 megabyte) 
           for the worst case song, which is certainly doable.

	   As memoization can be done efficiently when carried out sequentially, it can be done in O(n)

	   When this function is called once with last blocknum, all blocks can be memoized during a
	   single pass of the WHILE loop
           Lookup will be O(1). 
	   A typical song transfer will take X tracks 
           (each track requires a sector calc for all blocks).
*/

void hd24song::getmultitracksample(long* mtsample,int readmode)
{
	/* This procedure is intended for copying audio from disk (and for realtime
           playback). This procedure assumes sequential reading.

	   If reverse playback is desired, golocatepos() must be called for 
           every sample. This is a bit more expensive in resources.
	   However, as golocatepos() 
	   doesn't cause any I/O, it should still be light enough for regular use.

	   As such, allocation info for every sample will only be recalculated 
	   when needed. This results in the best possible performance.

	   There are two playback modes: copy and realtime. Copy mode guarantees
           that a bit-accurate copy of the disk contents is returned, but may
           require (slow) disk reads in the process, which makes it unsuitable
           for anything requiring realtime response.

           Realtime mode guarantees to return a result in a short amount of time, 
           by using a cache. This makes it suitable for realtime playback.
           When a block is not available in cache, silence is returned. This makes
           realtime mode unsuitable for accurate transfers, but suitable for direct
           from-disk mixing. Blocks that are not available in cache are queued for
           caching. Periodic background checks should be performed on this queue to
           help guarantee availability of the blocks to cache. 

	   In high samplerate mode, samples are interlaced between odd tracks and
	   even tracks. This allows the song cursor to keep running at normal speed-
	   the difference is that at double the speed the songcursor is only
 	   updated every other multitrack sample request. This means that at the
	   cost of only being able to do locate operations to even samples,
	   we can maintain use the same code for block calculation.
	*/
#if (SONGDEBUG==1)
	cout << "Getmultitracksample mtsample=" << mtsample <<" mode=" <<readmode<< "this=" <<this << endl;
	cout << "parentfs=" << parentfs << endl;
#endif
	unsigned char* buffertouse=NULL;
	currentreadmode=readmode;	
	__uint32 samrate=samplerate();
	__uint32 samplenumber=songcursor;	
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=physical_channels();
	__uint32 tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;
	__uint32 blocknum=(samplenumber/(tracksamples_per_block));
#if (SONGDEBUG==1)
	cout << "tracksamples per block="<<tracksamples_per_block << endl;
	cout << "readmtsample MARK" << endl;
#endif
	bool mustgetaudiodata=false;
	if (parentfs->maintenancemode==1) {
		readmode=hd24song::READMODE_COPY;
	}
	switch (readmode) 
	{
		case hd24song::READMODE_COPY:
			if ((lastreadblock!=blocknum)||(mustreadblock==1)) 
			{
				mustgetaudiodata=true;
			}
			break;
		case hd24song::READMODE_REALTIME:
			mustgetaudiodata=false;
			if ((lastavailablecacheblock!=blocknum)||(mustreadblock==1)) {
				mustgetaudiodata=true;
			}
			break;
		default: 
			mustgetaudiodata=false;
			break;
	}
	
#if (SONGDEBUG==1)
	cout << "readmtsample MARK2" << endl;
#endif
	if (mustgetaudiodata)
	{
		// We advanced a block. This means we need to read more audio data.
		// (or in case of realtime reading, at least find out what next block to get)
		if (blocknum==(allocstartblock+allocaudioblocks)) 
		{
			// In fact, we've read all data in the current allocation entry.
			allocentrynum++;			// reset cursor to start of song
			allocstartblock=blocknum; 	// blocknum of first block in current allocation entry
			allocstartsector=Convert::getint32(buffer,
				SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_SECTORNUM);
			allocaudioblocks=Convert::getint32(buffer,
				SONGINFO_ALLOCATIONLIST+(ALLOCINFO_ENTRYLEN*allocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);
		}
		
		switch (readmode) 
		{
			case (hd24song::READMODE_COPY):
				if (parentfs->maintenancemode==1) 
				{
                                        // in maintenance mode, we will display the sector currently
                                        // being played back (that is what maintenance mode is all
                                        // about

					string* bla=Convert::int32tohex(allocstartsector+((blocknum-allocstartblock)*blocksize_in_sectors));
					cout << *bla << "-1" << endl; // maintenance mode
					delete bla;
				}
				
				parentfs->readsectors(parentfs->devhd24,
				allocstartsector+((blocknum-allocstartblock)*blocksize_in_sectors),
				audiobuffer,blocksize_in_sectors); // raw audio read, no fstfix needed
				mustreadblock=0;
				break;
			case (hd24song::READMODE_REALTIME):
				buffertouse=getcachedbuffer(blocknum);
					
			default: break;
		}
	//	cout << "read done. " << endl;
	}
#if (SONGDEBUG==1)
	cout << "readmtsample MARK 3" << endl;
	cout << "audiobuffer=" << audiobuffer << endl;
	cout << "readmtsample MARK 3b" << endl;
#endif

	int sample_within_block=samplenumber%(tracksamples_per_block);
	if (readmode==hd24song::READMODE_COPY) 
	{
		buffertouse=audiobuffer;
	}
	__uint32 trackspersam;
	if (samrate>=88200) {
		trackspersam=2; 
	} else {
		trackspersam=1;
	}
#if (SONGDEBUG==1)
	cout << "readmtsample MARK 3c" << endl;
#endif
	__uint32 tottracks=logical_channels();
	for (__uint32 tracknum=0;tracknum<tottracks;tracknum++) 
	{
		__uint32 samval;
		if (buffertouse==NULL) 
		{
			samval=0;
		} 
		else 
		{
			int offset_first_blocksample=(((tracknum*trackspersam)+evenodd)*tracksamples_per_block*bytes_per_sample);
			int sample_offset=offset_first_blocksample+(sample_within_block*bytes_per_sample);
			samval=Convert::getint24(buffertouse,sample_offset);
			// TODO: Handle word lengths other than 24 bits
		}
#if (SONGDEBUG==1)
	cout << "readmtsample MARK 3e" << endl;
	cout << "tracknum=" << tracknum << endl;
#endif
		mtsample[tracknum]=samval;
#if ( SONGDEBUG == 1 )
	cout << "posttracknum=" << tracknum << endl;
		if ((tracknum==0) && (songcursor<20)) {
			string* bla=Convert::int32tohex(samval);
			cout << *bla << "-2"<< endl;
			delete bla;
		}
	cout << "readmtsample MARK 3f" << endl;
#endif
	}
#if (SONGDEBUG==1)
	cout << "readmtsample MARK 4" << endl;
#endif
	lastreadblock=blocknum;
	if (samrate>=88200) 
	{
		// only for high sample rate mode: 
		evenodd=1-evenodd;
		if (evenodd==0) {
			songcursor++;	
		}
	} else {
		songcursor++;
	}

	return;
}

int hd24song::getmtrackaudiodata(__uint32 firstsamnum,__uint32 samples,unsigned char* buffer,int readmode)
{
	/* WARNING: For best performance the number of samples must not cross
           audio block boundaries. This function has been tested in such a fashion only.

           This procedure is intended for reading audio data from disk,
	   in a completely random access fashion.
	   It assumes single track audio and will always read only whole blocks,
           directly to the given buffer. Return value is a pointer to the
           first sample that was supposed to be read.
 
	   The buffer should be sufficiently large to hold the total audio size.
  	   (number of samples*3 bytes for normal sample rates or
            number of samples*3*2 bytes for high sample rates (88k2, 96k).

	   In copy mode, only required blocks will be read from disk
           (no caching will take place- we'll leave this to the OS)

           Realtime mode guarantees to return a result in a short amount of time, 
           by using a cache. This makes it suitable for realtime playback.
           REALTIME MODE IS NOT IMPLEMENTED YET.
           When a block is not available in cache, silence is returned. This makes
           realtime mode unsuitable for accurate transfers, but suitable for direct
           from-disk mixing. Blocks that are not available in cache are queued for
           caching. Periodic background checks should be performed on this queue to
           help guarantee availability of the blocks to cache. 
        */

	currentreadmode=readmode;	
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;

	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=logical_channels();
	__uint32 tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;

	__uint32 startblocknum=((firstsamnum-(firstsamnum%tracksamples_per_block))/(tracksamples_per_block));
	__uint32 lastsamnum=firstsamnum+samples-1;
	__uint32 endblocknum=((lastsamnum-(lastsamnum%tracksamples_per_block))/(tracksamples_per_block));

	// check read enable flags to allow reducing number of sectors to be transferred.
	__uint32 first_readenabled=0;
	__uint32 last_readenabled=23;
	for (__uint32 i=0;i<logical_channels();i++)
	{
		if (track_readenabled[i])
		{
			first_readenabled=i;
			break;
		}
	}
	for (__uint32 i=logical_channels();i>0;i--)
	{
		if (track_readenabled[i-1])
		{
			last_readenabled=i-1;
			break;
		}
	}
#if (SONGDEBUG==1)
	cout << "first,last track="<<first_readenabled<<","<<last_readenabled<<endl;
#endif
	__uint32 chanmult=physical_channels()/logical_channels();

	__uint32 physicaltracksreadenabled=chanmult*(last_readenabled-first_readenabled)+1;
	__uint32 firsttrackoffset=chanmult*first_readenabled*tracksamples_per_block*bytes_per_sample;
	__uint32 sectoroffset=firsttrackoffset/SECTORSIZE;
	__uint32 readlength=(physicaltracksreadenabled*bytes_per_sample*tracksamples_per_block)/SECTORSIZE;
#if (SONGDEBUG==1)
	cout << "sectoroffset,readlength="<<sectoroffset<<","<<readlength<< endl;
#endif
	for (__uint32 blocknum=startblocknum;blocknum<=endblocknum;blocknum++) 
	{
#if (SONGDEBUG == 1)
			string* bla=Convert::int32tohex(blocksector[blocknum]);
			cout << *bla << "-3" << endl; // maintenance mode
			delete bla;
#endif
		// now read trackblocksize_in_sectors sectors from sector blocksec into buffer
		parentfs->readsectors(parentfs->devhd24,
			blocksector[blocknum]+sectoroffset,
			&buffer[firsttrackoffset],
			readlength); // raw audio read, no fstfix needed
	}
	return firstsamnum%tracksamples_per_block;
}

void hd24song::interlaceblock(unsigned char* sourcebuffer,unsigned char* targetbuffer) 
{
	/* This is needed for high sample rates as high sample rate recordings
           take up two physical channels for each logical audio channel */
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 blocksize_doubleblock=blocksize_in_bytes/logical_channels();
	__uint32 blocksize_halfblock=blocksize_in_bytes/physical_channels();

	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracksamples_per_halfblock=(blocksize_halfblock/bytes_per_sample);
	__uint32 choffset=0;
	for (__uint32 ch=0;ch<logical_channels();ch++) 
	{	
		for (__uint32 i=0;i<tracksamples_per_halfblock;i++) 
		{
			__uint32 samoff_target=i*bytes_per_sample+choffset;
			__uint32 samoff_source=2*i*bytes_per_sample+choffset;
			for (__uint32 j=0;j<bytes_per_sample;j++) {	
				targetbuffer[samoff_target+j]
					=sourcebuffer[samoff_source+j];
				targetbuffer[samoff_target+j+bytes_per_sample]
					=sourcebuffer[samoff_source+j+blocksize_halfblock];
			}
		}
		choffset+=blocksize_doubleblock;
	}
}

void hd24song::deinterlaceblock(unsigned char* sourcebuffer,unsigned char* targetbuffer) 
{
	/* This is needed for high sample rates as high sample rate recordings
           take up two physical channels for each logical audio channel */	
	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;
	__uint32 blocksize_doubleblock=blocksize_in_bytes/logical_channels();
	__uint32 blocksize_halfblock=blocksize_in_bytes/physical_channels();

	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracksamples_per_halfblock=(blocksize_halfblock/bytes_per_sample);
	__uint32 choffset=0;
	for (__uint32 ch=0;ch<logical_channels();ch++) 
	{	
		for (__uint32 i=0;i<tracksamples_per_halfblock;i++) 
		{
			__uint32 samoff_source=i*bytes_per_sample+choffset;
			__uint32 samoff_target=2*i*bytes_per_sample+choffset;
			for (__uint32 j=0;j<bytes_per_sample;j++) {	
				targetbuffer[samoff_target+j]
					=sourcebuffer[samoff_source+j];
				targetbuffer[samoff_target+j+bytes_per_sample]
					=sourcebuffer[samoff_source+j+blocksize_halfblock];
			}
		}
		choffset+=blocksize_doubleblock;
	}
}

int hd24song::putmtrackaudiodata(__uint32 firstsamnum,__uint32 samples,unsigned char* writebuffer,int writemode)
{
//	cout << " first 30 bytes of write buffer: " ;
//	for (int i=0;i<30;i++) { cout << " " << (short)((unsigned char)writebuffer[i]); }
//	cout << endl;
	/* 
           This procedure is intended for writing audio data to disk.
           Contrary to reading audio (where realtime mode is OK to drop
           some audio during heavy seeking), write mode should always
           write reliably- caching is not allowed.
           As such only sequential operation is allowed.

           NOTE: THIS FUNCTION WAS NOT TESTED FOR REALTIME OPERATION.
           
           Before writing, you need to arm the tracks that you want to
           write to (using the unarmtrack and armtrack functions),
           then enable record mode (function startrecord). 

           Startrecord will disable seeking while recording and perform
           any tasks needed to initialize drive usage administration.

           When no tracks are armed or record mode is not enabled, 
           nothing will be written to disk. (A rehearse mode may be
           added at some point to prevent writing to disk even in
 	   record mode).

           After writing, you need to call stoprecord. This will
           re-enable seek operations and write out any drive usage
           information, increase file length etc, should any space have 
    	   been allocated during the write operation.

           Before calling this function, the write buffer needs to contain
           the audio to record in the tracks that are armed.

           After calling this function, the write buffer contents will be
           altered: the non-armed tracks will contain the audio that
           was already on disk.

           The write buffer should be sufficiently large to hold the total
           audio size for all tracks.

        */

	currentreadmode=writemode;

	__uint32 blocksize_in_sectors=parentfs->getblocksizeinsectors();
	__uint32 blocksize_in_bytes=blocksize_in_sectors*SECTORSIZE;

	__uint32 bits=(this->bitdepth());
	__uint32 bytes_per_sample=bits/8;
	__uint32 tracks_per_song=logical_channels();
	__uint32 tracksamples_per_block=(blocksize_in_bytes / bytes_per_sample) / tracks_per_song;
	__uint32 trackbytes_per_block=(blocksize_in_bytes / tracks_per_song);

	__uint32 startblocknum=((firstsamnum-(firstsamnum%tracksamples_per_block))/(tracksamples_per_block));
	__uint32 lastsamnum=firstsamnum+samples-1;
	__uint32 endblocknum=((lastsamnum-(lastsamnum%tracksamples_per_block))/(tracksamples_per_block));
	for (__uint32 blocknum=startblocknum;blocknum<=endblocknum;blocknum++) 
	{
		// now read trackblocksize_in_sectors sectors from sector blocksec into buffer
		//cout << "Reading sec " << blocksector[blocknum] << endl;

		if (blocksector[blocknum]<0x1397f6) {
			// safety feature- drop out of write mode when superblock is targeted.
			cout << "Detected audio write request to administration area. " << endl;
			cout << "Possible bug, dropping out of write mode. " << endl;
			setrehearsemode(true);
		}
		
		parentfs->readsectors(parentfs->devhd24,
			blocksector[blocknum],
			scratchbook,
			blocksize_in_sectors); // raw audio read, no fstfix needed

		// now overwrite only the armed tracks with contents of buffer
		__uint32 numtracks=0;
		if (!(this->isrehearsemode())) {

			for (__uint32 tracknum=1; tracknum<=tracks_per_song; tracknum++) {
				if (!(this->trackarmed(tracknum))) {
					continue;
				}
				numtracks++;
				//cout << "track "<<tracknum<<" is armed." <<endl;
				__uint32 firsttrackbyte=(tracknum-1)*trackbytes_per_block;
				for (__uint32 q=0; q<trackbytes_per_block;q++) {
					if (q<10) {
//nn					cout << "scratchbook[" << firsttrackbyte+q <<"]=writebuffer[dito]=" << (int)((unsigned char)writebuffer[firsttrackbyte+q]) << endl;
					}
					scratchbook[firsttrackbyte+q]=(unsigned char)writebuffer[firsttrackbyte+q];
				}
			}
			if (numtracks>0) {		
				//cout << "writing back " << numtracks 
				// << " tracks to sector "<< blocksector[blocknum] << endl;
				parentfs->writesectors(parentfs->devhd24,
					blocksector[blocknum],
					scratchbook,
					blocksize_in_sectors);
			}
		}
	}
	return firstsamnum%tracksamples_per_block;
}

void hd24song::startrecord(int recordmode)
{
	// TODO: recordmode to distinguish between realtime and copy mode
	recordmode=recordmode;
	this->busyrecording=true;
}

void hd24song::stoprecord()
{
	this->busyrecording=false;
}

bool hd24song::recording()
{
	return (this->busyrecording);
}


void hd24song::readenabletrack(__uint32 tracknum,bool enable) 
{
	if (tracknum<1) return;
	if (tracknum>24) return;
	if (tracknum>logical_channels()) return;
	track_readenabled[tracknum-1]=enable;
}

void hd24song::readenabletrack(__uint32 tracknum)
{
	readenabletrack(tracknum,true);
}

bool hd24song::isrehearsemode()
{
	return this->rehearsemode;
}

void hd24song::setrehearsemode(bool p_rehearsemode)
{
	this->rehearsemode=p_rehearsemode;
	return;
}

void hd24song::trackarmed(__uint32 tracknum,bool arm) 
{
	if (tracknum<1) return;
	if (tracknum>24) return;
	if (tracknum>logical_channels()) return;
	track_armed[tracknum-1]=arm;
	return;
}

bool hd24song::trackarmed(__uint32 tracknum) 
{
	if (tracknum<1) return false;
	if (tracknum>24) return false;
	return track_armed[tracknum-1];
}

bool hd24song::istrackmonitoringinput(__uint32 tracknum)
{
	// TODO: PROPERLY SET TRANSPORT STATUS! (for now done by GUI)

	if (tracknum<1) return false;
	if (tracknum>(this->logical_channels())) return false;

	// indicates if a given track is (supposed to be)
	// monitoring input (if false, playback is being monitored). 
	// This is based on the following decision matrix:
        //
	// All input | auto input | Track rec-enabled | Transport status | result
        // ----------+------------+-------------------+------------------+--------
        //  on       |            | don't care        | don't care       | true
        //  off      | off        | false             | stop             | false 
        //  off      | off        | false             | play             | false
        //  off      | off        | false             | rec              | false
        //  off      | off        | true              | stop             | true
        //  off      | off        | true              | play             | true
        //  off      | off        | true              | rec              | true
        //  off      | on         | false             | stop             | false
        //  off      | on         | false             | play             | false
        //  off      | on         | false             | rec              | false
        //  off      | on         | true              | stop             | true
        //  off      | on         | true              | play             | false
        //  off      | on         | true              | rec              | true
        // ----------+------------+-------------------+------------------+--------
	if (parentfs->isallinput()) {
		return true;
	}
	if (!(this->trackarmed(tracknum))) return false;

	if (this->parentfs->transportstatus==hd24fs::TRANSPORTSTATUS_PLAY) {
		if (this->parentfs->isautoinput()) {	
			return false;
		}
	}
	return true;
}

__uint32 hd24song::getnextfreesector(__uint32 lastallocsector)
{
	/* Based on the alloc info of the current song, this function
	   will return the sector number of the next unallocated cluster.
	   When no unallocated sectors are found, the function will return 0.

           Sector 0 is never in the data area, so this will allow us to 
	   distinguish between this situation and real cluster numbers.
	   Sector 0 is the superblock- as allocation implies writing to the
           drive, the code calling this function MUST verify the result. 
	  
           When the allocation info cannot be decided upon based on just
           the unallocated song sectors within the last allocated cluster
           for the song, this function will ask the file system for the
           sector number of the next unused cluster.
           
	*/
#if (SONGDEBUG==1)
	cout << "Song::getnextfreesec(" << lastallocsector << ")" << endl;
#endif
	// lastallocentrynum=last used allocation entry
        __uint32 allocsector=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST
		+(ALLOCINFO_ENTRYLEN*lastallocentrynum)+ALLOCINFO_SECTORNUM);
        __uint32 allocblocks=Convert::getint32(buffer,SONGINFO_ALLOCATIONLIST
		+(ALLOCINFO_ENTRYLEN*lastallocentrynum)+ALLOCINFO_AUDIOBLOCKSINBLOCK);
	__uint32 nextsec=0;
	
	if ((allocsector==0) && (lastallocsector==0))
	{
		// no sectors allocated yet within song.
		nextsec=this->parentfs->getnextfreesector(CLUSTER_UNDEFINED);
	} else {	
		// find out first cluster used by allocation unit
		__uint32 alloccluster;
		__uint32 blockspercluster;
		__uint32 clustersused;
		__uint32 lastalloccluster;
		if (allocsector==0) {
			lastalloccluster=parentfs->sector2cluster(lastallocsector);
		} else {
			alloccluster=parentfs->sector2cluster(allocsector);
			blockspercluster=parentfs->getblockspercluster();
			clustersused=allocblocks/blockspercluster;
			lastalloccluster=alloccluster+(clustersused-1);
		}

		// check if allocation entry fills up the current cluster word
		// if not, allocate another cluster within current alloc entry
		// otherwise, ask the FS for drive space
		// (update song alloc info)

		nextsec=this->parentfs->getnextfreesector(lastalloccluster);
	}

	if (nextsec==0) 
	{
	   /* 
		TODO: safety feature: If getnextfreesector returns 0, record
          	mode will be disabled to prevent accidentally overwriting the 
           	superblock. (Alternatively transport may be stopped but 
           	auto-stop hasn't been fully designed yet). */
		// write protect of some sort
		setrehearsemode(true);
	} 
	return nextsec;
}

void hd24song::save()
{
	__uint32 songsector=parentproject->getsongsectornum(this->mysongid);
#if (SONGDEBUG == 1)
	cout << "writing buffer to sector " << songsector << ", " <<TOTAL_SECTORS_PER_SONG<<" sectors" << endl;
#endif

	parentfs->fstfix(buffer,TOTAL_SECTORS_PER_SONG*512); // sector is now once again in native format

	parentfs->setsectorchecksum(buffer,0,songsector,2);     // checksum for 2 sectors of song data
	parentfs->setsectorchecksum(buffer,2*512,songsector+2,5); // checksum for 5 sectors of allocation data

	parentfs->writesectors(parentfs->devhd24,
			songsector,
			buffer,TOTAL_SECTORS_PER_SONG);
	
	parentfs->fstfix(buffer,TOTAL_SECTORS_PER_SONG*512); // sector is now in 'fixed' format again
	if (this->lengthened) 
	{
#if (SONGDEBUG == 1)
		cout << "song was lengthened, update of drive usage needed." << endl;
#endif
		parentfs->savedriveusage();
		this->lengthened=false;
	} else 
	{
#if (SONGDEBUG == 1)
		cout << "song was not lengthened, no update of drive usage needed." << endl;
#endif
	}
	parentfs->commit();
}