#import <musickit/musickit.h>
#import <sys/file.h>
#import "HybridInstrument.h"

void main(int ac, char *av[])
{
	int i, partCount;
	id aSFPerformer, hybridIns;
	double samplingRate = 22050.;
	int inFd, outFd;
	id scoreInfo, noteSenders;
	NXStream *inStream, *outStream;
	char bNormAmp = 1;

	if (ac != 3) 
	{
		fprintf(stderr,
		        "Usage: hybridMk <input score file> <output snd file>.\n");
		exit(1);
	}

	inFd = open(av[1],O_RDONLY,0660);	
	if (inFd == -1) 
	{
		fprintf(stderr,"Can't open %s\n.",av[1]);
		exit(1);
	} 
	else fprintf(stderr,"Input file: %s\n",av[1]);

	outFd = open(av[2], O_RDWR | O_CREAT | O_TRUNC, 0660);	
	if (outFd == -1) 
	{
		fprintf(stderr,"Can't create %s\n.",av[2]);
		exit(1);
	} 
	else fprintf(stderr,"Output file: %s\n",av[2]);

	inStream = NXOpenFile(inFd,NX_READONLY);
	outStream = NXOpenFile(outFd,NX_READWRITE); 
    
	aSFPerformer = [[ScorefilePerformer alloc] init];	
	[aSFPerformer setStream:inStream];		
	[aSFPerformer activate]; 
	scoreInfo = [aSFPerformer info];
	if (scoreInfo) 
	{  
		if ([scoreInfo isParPresent:MK_samplingRate])
			if (((samplingRate = [scoreInfo parAsDouble:MK_samplingRate]) !=
			     22050.) && (samplingRate != 44100.))
				fprintf(stderr,"This samplingRate is not allowed, set to %g.\n", 
				        samplingRate); 
		if ([scoreInfo isParPresent:[Note parName:"normalizeAmp"]])
			bNormAmp = (char)[scoreInfo parAsInt:[Note parName:"normalizeAmp"]];

	}

	hybridIns = [[HybridInstrument alloc] init];
	[hybridIns setSamplingRate:samplingRate normal:bNormAmp stream:outStream];
	noteSenders = [aSFPerformer noteSenders];
	partCount = [noteSenders count];	// conta las parts, i per cada una
	for (i = 0; i < partCount; i++)	 	
		[[noteSenders objectAt:i] connect:[hybridIns noteReceiver]];
   
	[noteSenders free];

	[Conductor setClocked:NO];
	fprintf(stderr,"hybridizing...\n");
	[Conductor startPerformance];

 	fprintf(stderr,"...done\n");
	NXClose(outStream);
	exit(0);
}