File: sidtune.cpp

package info (click to toggle)
sidplay 1.36.28-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,192 kB
  • ctags: 1,674
  • sloc: cpp: 12,514; sh: 1,716; makefile: 223
file content (972 lines) | stat: -rw-r--r-- 24,976 bytes parent folder | download
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
//
// /home/ms/source/sidplay/libsidplay/RCS/sidtune.cpp,v
//
// Information on usage of this class in "include/sidtune.h".
//

#include <iostream.h>
#include <iomanip.h>
#include <string.h>
#include <limits.h>

#include "sidtune.h"
#include "fformat.h"
#include "myendian.h"
#include "pp.h"


const char text_songNumberExceed[] = "WARNING: Selected song number was too high";
const char text_emptyFile[] = "ERROR: File is empty";
const char text_unrecognizedFormat[] = "ERROR: Could not determine file format";
const char text_noDataFile[] = "ERROR: Did not find the corresponding data file";
const char text_notEnoughMemory[] = "ERROR: Not enough free memory";
const char text_cantLoadFile[] = "ERROR: Could not load input file";
const char text_cantOpenFile[] = "ERROR: Could not open file for binary input";
const char text_fileTooLong[] = "ERROR: Input data too long";
const char text_dataTooLong[] = "ERROR: Music data size exceeds C64 memory";
const char text_cantCreateFile[] = "ERROR: Could not create output file";
const char text_fileIoError[] = "ERROR: File I/O error";
const char text_fatalInternal[] = "FATAL: Internal error - contact the developers";
const char text_PAL_VBI[] = "50 Hz VBI (PAL)";
const char text_PAL_CIA[] = "CIA 1 Timer A (PAL)";
const char text_NTSC_VBI[] = "60 Hz VBI (NTSC)";
const char text_NTSC_CIA[] = "CIA 1 Timer A (NTSC)";
const char text_noErrors[] = "No errors";
const char text_na[] = "N/A";

// Default sidtune file name extensions. This selection can be overriden
// by specifying a custom list in the constructor.
const char *defaultFileNameExt[] =
{
	// Preferred default file extension for single-file sidtunes
	// or sidtune description files in SIDPLAY INFOFILE format.
	".sid",
	// Common file extension for single-file sidtunes due to SIDPLAY/DOS
	// displaying files *.DAT in its file selector by default.
	// Originally this was intended to be the extension of the raw data file
	// of two-file sidtunes in SIDPLAY INFOFILE format.
	".dat",
	// Extension of Amiga Workbench tooltype icon info files, which
	// have been cut to MS-DOS file name length (8.3).
	".inf",
	// No extension for the raw data file of two-file sidtunes in
	// PlaySID Amiga Workbench tooltype icon info format.
	"",
	// Common upper-case file extensions from MS-DOS (unconverted).
	".DAT", ".SID", ".INF",
	// File extensions used (and created) by various C64 emulators and
	// related utilities. These extensions are recommended to be used as
	// a replacement for ".dat" in conjunction with two-file sidtunes.
	".c64", ".prg", ".C64", ".PRG",
	// Uncut extensions from Amiga.
	".info", ".INFO", ".data", ".DATA",
	// End.
	0
};

// ------------------------------------------------- constructors, destructor

sidTune::sidTune( const char* fileName, const char **fileNameExt )
{
	safeConstructor();
	if ( fileNameExt != 0 )
	{
		fileNameExtensions = fileNameExt;
	}
	if (fileName != 0)
	{
#if !defined(NO_STDIN_LOADER)
		// Filename ``-'' is used as a synonym for standard input.
		if ( strcmp( fileName, "-" ) == 0 )
		{
			stdinConstructor();
		}
		else
		{
#endif
			filesConstructor( fileName );
#if !defined(NO_STDIN_LOADER)
		}
#endif
		deleteFileBuffers();
	}
}


sidTune::sidTune(const ubyte* data, udword dataLen)
{
	safeConstructor();
	bufferConstructor(data,dataLen);
}


sidTune::~sidTune()
{
	safeDestructor();
}


// -------------------------------------------------- public member functions

bool sidTune::load(const ubyte* data, udword dataLen)
{
	safeDestructor();
	safeConstructor();
	bufferConstructor(data,dataLen);
	return status;
}

bool sidTune::open(const char* fileName)
{
	safeDestructor();
	safeConstructor();
	filesConstructor(fileName);
	deleteFileBuffers();
	return status;
}

bool sidTune::setInfo( sidTuneInfo & inInfo )
{
    // dummy
    return true;
}

bool sidTune::getInfo( sidTuneInfo& outInfo )
{
	outInfo = info;
	return true;
}

// First check, whether a song is valid. Then copy any song-specific
// variable information such a speed/clock setting to the info structure.
//
// This is a private member function. It is used only by player.cpp.
uword sidTune::selectSong(uword selectedSong)
{
	// Determine and set starting song number.
	if (selectedSong == 0)
	{
		selectedSong = info.startSong;
	}
	else if ((selectedSong > info.songs) || (selectedSong > classMaxSongs))
	{
		info.statusString = text_songNumberExceed;
		selectedSong = info.startSong;
	}
	info.lengthInSeconds = songLength[selectedSong-1];
	// Retrieve song speed definition.
	info.songSpeed = songSpeed[selectedSong-1];
	info.clockSpeed = clockSpeed[selectedSong-1];
	// Assign song speed description string depending on clock speed.
	if (info.clockSpeed == SIDTUNE_CLOCK_PAL)
	{
		if (info.songSpeed == SIDTUNE_SPEED_VBI)
		{
			info.speedString = text_PAL_VBI;
		}
		else
		{
			info.speedString = text_PAL_CIA;
		}
	}
	else  //if (info.clockSpeed == SIDTUNE_CLOCK_NTSC)
	{
		if (info.songSpeed == SIDTUNE_SPEED_VBI)
		{
			info.speedString = text_NTSC_VBI;
		}
		else
		{
			info.speedString = text_NTSC_CIA;
		}
	}
	return (info.currentSong=selectedSong);
}

void sidTune::fixLoadAddress(bool force, uword init, uword play)
{
    if (info.fixLoad || force)
    {
        info.fixLoad = false;
        info.loadAddr += 2;
        fileOffset += 2;

        if (force)
        {
            info.initAddr = init;
            info.playAddr = play;
        }
    }
}


// ------------------------------------------------- private member functions

void sidTune::setIRQaddress(uword address)
{
	info.irqAddr = address;
}

bool sidTune::placeSidTuneInC64mem( ubyte* c64buf )
{
	if (isCached && status)
	{
		// Check the size of the data.
		if ( info.c64dataLen > 65536 )
		{
			info.statusString = text_dataTooLong;
			return (status = false);
		}
		else
		{
			udword endPos = info.loadAddr + info.c64dataLen;
			if (endPos <= 65536)
			{
				// Copy data from cache to the correct destination.
				memcpy(c64buf+info.loadAddr,cachePtr+fileOffset,info.c64dataLen);
			}
			else
			{
				// Security - split data which would exceed the end of the C64 memory.
				// Memcpy could not detect this.
				memcpy(c64buf+info.loadAddr,cachePtr+fileOffset,info.c64dataLen-(endPos-65536));
				// Wrap the remaining data to the start address of the C64 memory.
				memcpy(c64buf,cachePtr+fileOffset+info.c64dataLen-(endPos-65536),(endPos-65536));
			}
			return (status = true);
		}
	}
	else
	{
		return (status = false);
	}
}


udword sidTune::loadFile(const char* fileName, ubyte** bufferRef)
{
	udword fileLen = 0;
	status = false;
	// Open binary input file stream at end of file.
#if defined(HAVE_IOS_BIN)
	ifstream myIn( fileName, ios::in | ios::bin | ios::ate | ios::nocreate );
#else
	ifstream myIn( fileName, ios::in | ios::binary | ios::ate | ios::nocreate );
#endif
	// As a replacement for !is_open(), bad() and the NOT-operator don't seem
	// to work on all systems.
#if defined(DONT_HAVE_IS_OPEN)
    if ( !myIn )
#else
	if ( !myIn.is_open() )
#endif
	{
		info.statusString = text_cantOpenFile;
	}
	else
	{
		// Check for PowerPacker compression: load and decompress, if PP20 file.
		if (depp(myIn,bufferRef))
		{
			// Decompression successful, use uncompressed datafilelen.
			fileLen = ppUncompressedLen();
			info.statusString = ppErrorString;
			status = true;
		}
		else if (ppIsCompressed())
		{
			// An error occured while decompressing.
			info.statusString = ppErrorString;
		}
		else  // should be uncompressed file
		{
#if defined(HAVE_SEEKG_OFFSET)
			fileLen = (myIn.seekg(0,ios::end)).offset();
#else
			myIn.seekg(0, ios::end);
			fileLen = (udword)myIn.tellg();
#endif
			if ( *bufferRef != 0 )
			{
				delete[] *bufferRef;  // free previously allocated memory
			}
			*bufferRef = new ubyte[fileLen+1];
			if ( *bufferRef == 0 )
			{
				info.statusString = text_notEnoughMemory;
				fileLen = 0;  // returning 0 = error condition.
			}
			else
			{
				*(*bufferRef+fileLen) = 0;
			}
			// Load uncompressed file.
			myIn.seekg(0, ios::beg);
			udword restFileLen = fileLen;
			while ( restFileLen > INT_MAX )
			{
				myIn.read( (ubyte*)*bufferRef + (fileLen - restFileLen), INT_MAX );
				restFileLen -= INT_MAX;
			}
			if ( restFileLen > 0 )
			{
				myIn.read( (ubyte*)*bufferRef + (fileLen - restFileLen), restFileLen );
			}
			if ( myIn.bad() )
			{
				info.statusString = text_cantLoadFile;
			}
			else
			{
				info.statusString = text_noErrors;
				status = true;
			}
		}
		myIn.close();
        if (fileLen == 0)
        {
            info.statusString = text_emptyFile;
            status = false;
        }
	}
	return fileLen;
}


void sidTune::deleteFileBuffers()
{
	// This function does not affect status and statusstring.
	// The filebuffers are global to the object.
	if ( fileBuf != 0 )
	{
		delete[] fileBuf;
		fileBuf = 0;
	}
	if ( fileBuf2 != 0 )
	{
		delete[] fileBuf2;
		fileBuf2 = 0;
	}
}

void sidTune::deleteFileNameCopies()
{
	// When will it be fully safe to call delete[] (0)?
	if ( info.dataFileName != 0 )
		delete[] info.dataFileName;
	if ( info.infoFileName != 0 )
		delete[] info.infoFileName;
	if ( info.path != 0 )
		delete[] info.path;
	info.dataFileName = 0;
	info.infoFileName = 0;
	info.path = 0;
}


bool sidTune::cacheRawData(const void* sourceBuf, udword sourceBufLen)
{
	clearCache();
	if ( (cachePtr = new ubyte[sourceBufLen]) == 0 )
	{
		info.statusString = text_notEnoughMemory;
		return (status = false);
	}
	else
        {
            if (sourceBufLen >= 2)
            {
                // We only detect an offset of two. Some position independent
                // sidtunes contain a load address of 0xE000, but are loaded
                // to 0x0FFE and call player at 0x1000.
                info.fixLoad = (readLEword((const ubyte*)sourceBuf+fileOffset)==(info.loadAddr+2));
            }
		memcpy(cachePtr, (const ubyte*)sourceBuf, sourceBufLen);
		cacheLen = sourceBufLen;
		isCached = true;
		info.statusString = text_noErrors;
		return (status = true);
	}
}

void sidTune::clearCache()
{
	if ( cachePtr != 0 )
	{
		delete[] cachePtr;
		cachePtr = 0;
	}
	cacheLen = 0;
	isCached = false;
}

bool sidTune::getCachedRawData( void* destBuf, udword destBufLen )
{
	if (( cachePtr == 0 ) || ( cacheLen > destBufLen ))
	{
		info.statusString = text_fatalInternal;
		return (status = false);
	}
	memcpy( (ubyte*)destBuf, cachePtr, cacheLen );
	info.dataFileLen = cacheLen;
	info.statusString = text_noErrors;
	return (status = true);
}


void sidTune::safeConstructor()
{
	// Initialize the object with some safe defaults.
	status = false;

	info.statusString = text_na;
	info.path = info.infoFileName = info.dataFileName = 0;
	info.dataFileLen = info.c64dataLen = 0;
	info.formatString = text_na;
	info.speedString = text_na;
	info.loadAddr = ( info.initAddr = ( info.playAddr = 0 ));
	info.songs = ( info.startSong = ( info.currentSong = 0 ));
	info.musPlayer = false;
	info.fixLoad = false;
	info.songSpeed = SIDTUNE_SPEED_VBI;
	info.clockSpeed = SIDTUNE_CLOCK_PAL;
	info.lengthInSeconds = 0;
	
	for ( uint si = 0; si < classMaxSongs; si++ )
	{
		songSpeed[si] = SIDTUNE_SPEED_VBI;
		clockSpeed[si] = SIDTUNE_CLOCK_PAL;
		songLength[si] = 0;
	}

	cachePtr = 0;
	cacheLen = 0;

	fileBuf = ( fileBuf2 = 0 );
	fileOffset = 0;
	fileNameExtensions = defaultFileNameExt;

	for ( uint sNum = 0; sNum < infoStringNum; sNum++ )
	{
		for ( uint sPos = 0; sPos < infoStringLen; sPos++ )
		{
			infoString[sNum][sPos] = 0;
		}
	}
	info.numberOfInfoStrings = 0;

	// Not used!!!
	info.numberOfCommentStrings = 1;
	info.commentString = new char* [info.numberOfCommentStrings];
	info.commentString[0] = myStrDup("--- SAVED WITH SIDPLAY ---");
}


void sidTune::safeDestructor()
{
	// Remove copy of comment field.
	udword strNum = 0;
	// Check and remove every available line.
	while (info.numberOfCommentStrings-- > 0)
	{
		if (info.commentString[strNum] != 0)
		{
			delete[] info.commentString[strNum];
			info.commentString[strNum] = 0;
		}
		strNum++;  // next string
	};
	delete[] info.commentString;  // free the array pointer

	clearCache();
	deleteFileNameCopies();
	deleteFileBuffers();

	status = false;
}


#if !defined(NO_STDIN_LOADER)

void sidTune::stdinConstructor()
{
	// Assume a failure, so we can simply return.
	status = false;
	// Assume the memory allocation to fail.
	info.statusString = text_notEnoughMemory;
	if (( fileBuf = new ubyte[65536] ) == 0 )
		return;
	uword i = 0;
	ubyte datb;
	while ( cin.get(datb) )
		fileBuf[i++] = datb; // uword index will wrap when > 65535
	if (( info.dataFileLen = cin.tellg() ) > 65536 )
	{
		info.statusString = text_fileTooLong;
	}
	else
	{
		getSidtuneFromFileBuffer(fileBuf,info.dataFileLen);
	}
	deleteFileBuffers();
}

#endif


void sidTune::bufferConstructor(const ubyte* data, udword dataLen)
{
	// Assume a failure, so we can simply return.
	status = false;
	if (data != 0)
	{
		if (dataLen > maxSidtuneFileLen)
		{
			info.statusString = text_fileTooLong;
		}
		else
		{
			info.dataFileLen = dataLen;
			getSidtuneFromFileBuffer(data, dataLen);
		}
	}
}

bool sidTune::getSidtuneFromFileBuffer(const ubyte* buffer, udword bufferLen)
{
	bool foundFormat = false;
	// Here test for the possible single file formats. ------------------
	if ( PSID_fileSupport( buffer, bufferLen ))
	{
		foundFormat = true;
	}
	else if ( MUS_fileSupport( buffer, bufferLen ))
	{
		foundFormat = true;
	}
	else
	{
		// No further single-file-formats available. --------------------
		info.formatString = text_na;
		info.statusString = text_unrecognizedFormat;
		status = false;
	}
	if ( foundFormat )
	{
		status = true;
		info.statusString = text_noErrors;
		acceptSidTune("-","-",buffer,bufferLen);
	}
	return foundFormat;
}


void sidTune::acceptSidTune(const char* dataFileName, const char* infoFileName,
                            const ubyte* dataBuf, udword dataLen )
{
	deleteFileNameCopies();
	// Make a copy of the data file name and path, if available.
	if ( dataFileName != 0 )
	{
		info.path = myStrDup(dataFileName);
        info.dataFileName = myStrDup(fileNameWithoutPath(info.path));
		*fileNameWithoutPath(info.path) = 0;  // path only
		if ((info.path==0) || (info.dataFileName==0))
		{
			info.statusString = text_notEnoughMemory;
			status = false;
			return;
		}
	}
	// Make a copy of the info file name, if available.
	if ( infoFileName != 0 )
	{
		char* tmp = myStrDup(infoFileName);
        info.infoFileName = myStrDup(fileNameWithoutPath(tmp));
		if ((tmp==0) || (info.infoFileName==0))
		{
			info.statusString = text_notEnoughMemory;
			status = false;
			return;
		}
		delete[] tmp;
	}
	// Fix bad sidtune set up.
	if (info.songs > classMaxSongs)
		info.songs = classMaxSongs;
	else if (info.songs == 0)
		info.songs++;
	if (info.startSong > info.songs)
		info.startSong = 1;
	else if (info.startSong == 0)
		info.startSong++;
	info.dataFileLen = dataLen;
	info.c64dataLen = dataLen - fileOffset;
	cacheRawData( dataBuf, dataLen );
}


bool sidTune::createNewFileName( char** destStringPtr,
                                 const char* sourceName,
                                 const char* sourceExt)
{
	// Free any previously allocated object.
	if ( *destStringPtr != 0 )
	{
		delete[] *destStringPtr;
	}
	// Get enough memory, so we can appended the extension.
	*destStringPtr = new char[strlen(sourceName) + strlen(sourceExt) +1];
	if ( *destStringPtr == 0 )
	{
		info.statusString = text_notEnoughMemory;
		return (status = false);
	}
	strcpy( *destStringPtr, sourceName );
	char* extPtr = fileExtOfPath(*destStringPtr);
	strcpy( extPtr, sourceExt );
	return true;
}


// Initializing the object based upon what we find in the specified file.

void sidTune::filesConstructor( const char* fileName )
{
	fileBuf = 0;  // will later point to the buffered file
	// Try to load the single specified file.
	if (( info.dataFileLen = loadFile(fileName,&fileBuf)) != 0 )
	{
		// File loaded. Now check if it is in a valid single-file-format.
		if ( PSID_fileSupport(fileBuf,info.dataFileLen ))
		{
			acceptSidTune(fileName,0,fileBuf,info.dataFileLen);
			return;
		}
		else if ( MUS_fileSupport(fileBuf,info.dataFileLen) )
		{
			acceptSidTune(fileName,0,fileBuf,info.dataFileLen);
			return;
		}


// -------------------------------------- Support for multiple-files formats.
		else
		{
// We cannot simply try to load additional files, if a description file was
// specified. It would work, but is error-prone. Imagine a filename mismatch
// or more than one description file (in another) format. Any other file
// with an appropriate file name can be the C64 data file.
// First we see if ``fileName'' could be a raw data file. In that case we
// have to find the corresponding description file.

			// Right now we do not have a second file. Hence the (0, 0, ...)
			// parameters are set for the data buffer. This will not hurt the
			// file support procedures.
			udword fileLen2;
			char* fileName2 = 0;

			// Make sure that ``fileBuf'' does not contain a description file.
			if ( !SID_fileSupport(0,0,fileBuf,info.dataFileLen) &&
				!INFO_fileSupport(0,0,fileBuf,info.dataFileLen) )
			{
				// Assuming ``fileName'' to hold the name of the raw data file,
				// we now create the name of a description file (=fileName2) by
				// appending various filename extensions.

// ------------------------------------------ Looking for a description file.

				const char **tmpFileNameExt = fileNameExtensions;
				while (*tmpFileNameExt != 0)
				{
					if ( !createNewFileName(&fileName2,fileName,*tmpFileNameExt) )
						return;
					// Do not load the first file again if names are equal.
					if ( stricmp(fileName,fileName2) != 0 )
					{
						// 1st data file was loaded into ``fileBuf'',
						// so we load the 2nd one into ``fileBuf2''.
						if (( fileLen2 = loadFile(fileName2,&fileBuf2)) != 0 )
						{
							if ( SID_fileSupport(fileBuf,info.dataFileLen,fileBuf2,fileLen2) )
							{
								acceptSidTune(fileName,fileName2,fileBuf,info.dataFileLen);
								delete[] fileName2;
								return;
							}
							else if ( INFO_fileSupport(fileBuf,info.dataFileLen,fileBuf2,fileLen2) )
							{
								acceptSidTune(fileName,fileName2,fileBuf,info.dataFileLen);
								delete[] fileName2;
								return;
							}
						}
					}
					tmpFileNameExt++;
				};

// --------------------------------------- Could not find a description file.

				delete[] fileName2;
				info.formatString = text_na;
				info.statusString = text_unrecognizedFormat;
				status = false;
				return;
			}


// -------------------------------------------------------------------------
// Still unsuccessful ? Probably one put a description file name into
// ``fileName''. Assuming ``fileName'' to hold the name of a description
// file, we now create the name of the data file and swap both used memory
// buffers - fileBuf and fileBuf2 - when calling the format support.
// If it works, the second file is the data file ! If it is not, but does
// exist, we are out of luck, since we cannot detect data files.

			// Make sure ``fileBuf'' contains a description file.
			else if ( SID_fileSupport(0,0,fileBuf,info.dataFileLen) ||
					 INFO_fileSupport(0,0,fileBuf,info.dataFileLen))
			{

// --------------------- Description file found. --- Looking for a data file.

				const char **tmpFileNameExt = fileNameExtensions;
				while (*tmpFileNameExt != 0)
				{
					if ( !createNewFileName(&fileName2,fileName,*tmpFileNameExt) )
						return;
					// Do not load the first file again if names are equal.
					if ( stricmp(fileName,fileName2) != 0 )
					{
						// 1st info file was loaded into ``fileBuf'',
						// so we load the 2nd one into ``fileBuf2''.
						if (( fileLen2 = loadFile(fileName2,&fileBuf2)) != 0 )
						{
// -------------- Some data file found, now identifying the description file.

							if ( SID_fileSupport(fileBuf2,fileLen2,fileBuf,info.dataFileLen) )
							{
								acceptSidTune(fileName2,fileName,fileBuf2,fileLen2);
								delete[] fileName2;
								return;
							}
							else if ( INFO_fileSupport(fileBuf2,fileLen2,fileBuf,info.dataFileLen) )
							{
								acceptSidTune(fileName2,fileName,fileBuf2,fileLen2);
								delete[] fileName2;
								return;
							}
						}
					}
					tmpFileNameExt++;
				};
				
// ---------------------------------------- No corresponding data file found.

				delete[] fileName2;
				info.formatString = text_na;
				info.statusString = text_noDataFile;
				status = false;
				return;
			} // end else if ( = is description file )

// --------------------------------- Neither description nor data file found.

			else
			{
				info.formatString = text_na;
				info.statusString = text_unrecognizedFormat;
				status = false;
				return;
			}
		} // end else ( = is no singlefile )

// ---------------------------------------------------------- File I/O error.

	} // if loaddatafile
	else
	{
		// returned fileLen was 0 = error. The info.statusString is
		// already set then.
		info.formatString = text_na;
		status = false;
		return;
	}
} 


void sidTune::convertOldStyleSpeedToTables(udword oldStyleSpeed)
{
	// Create the speed/clock setting tables.
	//
	// This does not take into account the PlaySID bug upon evaluating the
	// SPEED field. It would most likely break compatibility to lots of
	// sidtunes, which have been converted from .SID format and vice versa.
	// The .SID format does the bit-wise/song-wise evaluation of the SPEED
	// value correctly, like it is described in the PlaySID documentation.

	int toDo = ((info.songs <= classMaxSongs) ? info.songs : classMaxSongs);
	for (int s = 0; s < toDo; s++)
	{
		if (( (oldStyleSpeed>>(s&31)) & 1 ) == 0 )
		{
			songSpeed[s] = SIDTUNE_SPEED_VBI;
			clockSpeed[s] = SIDTUNE_CLOCK_PAL;
		}
		else
		{
			songSpeed[s] = SIDTUNE_SPEED_CIA_1A;
			clockSpeed[s] = SIDTUNE_CLOCK_PAL;
		}
	}
}


//
// File format conversion ---------------------------------------------------
//
				
bool sidTune::saveToOpenFile( ofstream& toFile, const ubyte* buffer, udword bufLen )
{
	udword lenToWrite = bufLen;
	while ( lenToWrite > INT_MAX )
	{
		toFile.write( buffer + (bufLen - lenToWrite), INT_MAX );
		lenToWrite -= INT_MAX;
	}
	if ( lenToWrite > 0 )
		toFile.write( buffer + (bufLen - lenToWrite), lenToWrite );
	if ( toFile.bad() )
	{
		info.statusString = text_fileIoError;
		return false;
	}
	else
	{
		info.statusString = text_noErrors;
		return true;
	}
}
		

bool sidTune::saveC64dataFile( const char* fileName, bool overWriteFlag )
{
	bool success = false;  // assume error
	// This prevents saving from a bad object.
	if ( status )
	{
		// Open binary output file stream.
		long int createAttr;
#if defined(HAVE_IOS_BIN)
		createAttr = ios::out | ios::bin;
#else
		createAttr = ios::out | ios::binary;
#endif
		if ( overWriteFlag )
			createAttr |= ios::trunc;
		else
			createAttr |= ios::noreplace;
		ofstream fMyOut( fileName, createAttr );
		if ( !fMyOut )
		{ 
			info.statusString = text_cantCreateFile;
		}
		else
		{  
			// Save c64 lo/hi load address.
			ubyte saveAddr[2];
			saveAddr[0] = info.loadAddr & 255;
			saveAddr[1] = info.loadAddr >> 8;
			fMyOut.write( saveAddr, 2 );
			// Data starts at: bufferaddr + fileOffset
			// Data length: info.dataFileLen - fileOffset
			if ( !saveToOpenFile( fMyOut, cachePtr + fileOffset, info.dataFileLen - fileOffset ) )
			{
				info.statusString = text_fileIoError;
			}
			else
			{
				info.statusString = text_noErrors;
				success = true;
			}
			fMyOut.close();
		}
	}
	return success;
}


bool sidTune::saveSIDfile( const char* fileName, bool overWriteFlag )
{
	bool success = false;  // assume error
	// This prevents saving from a bad object.
	if ( status )
	{
		// Open ASCII output file stream.
		long int createAttr;
		createAttr = ios::out;
		if ( overWriteFlag )
			createAttr |= ios::trunc;
		else
			createAttr |= ios::noreplace;
		ofstream fMyOut( fileName, createAttr );
		if ( !fMyOut )
		{ 
			info.statusString = text_cantCreateFile;
		}
		else
		{  
			if ( !SID_fileSupportSave( fMyOut ) )
			{
				info.statusString = text_fileIoError;
			}
			else
			{
				info.statusString = text_noErrors;
				success = true;
			}
			fMyOut.close();
		}
	}
	return success;
}
		

bool sidTune::savePSIDfile( const char* fileName, bool overWriteFlag )
{
	bool success = false;  // assume error
	// This prevents saving from a bad object.
	if ( status )
	{
		// Open binary output file stream.
		long int createAttr;
#if defined(HAVE_IOS_BIN)
		createAttr = ios::out | ios::bin;
#else
		createAttr = ios::out | ios::binary;
#endif
	  if ( overWriteFlag )
			createAttr |= ios::trunc;
		else
			createAttr |= ios::noreplace;
		ofstream fMyOut( fileName, createAttr );
		if ( !fMyOut )
		{
			info.statusString = text_cantCreateFile;
		}
		else
		{  
			if ( !PSID_fileSupportSave( fMyOut, cachePtr ) )
			{
				info.statusString = text_fileIoError;
			}
			else
			{
				info.statusString = text_noErrors;
				success = true;
			}
			fMyOut.close();
		}
	}
	return success;
}