
/* Generated by Interface Builder */

#import "MyObject.h"
#import <musickit/musickit.h>
#import <appkit/appkit.h>

@implementation MyObject

- init
{
    [super init];
    numQuarterNotes = 20;
    numEighthNotes = 20;
    numSixteenthNotes = 20;
    numPitchesEnabled = 5;
    tempo = 60;
    pitchMode[0] = 1; pitchMode[2] = 1; pitchMode[4] = 1; pitchMode[7] = 1;
    pitchMode[9] = 1;
    return self;
}

- setNumQuarterNotes:sender
{
    numQuarterNotes = [sender intValue];
    return self;
}

- setNumEighthNotes:sender
{
    numEighthNotes = [sender intValue];
    return self;
}

- setNumSixteenthNotes:sender
{
    numSixteenthNotes = [sender intValue];
    return self;
}

- setTempoFrom:sender
{
    tempo = [sender doubleValue];
    return self;
}

- setMode:sender
{
    int whichCell = [sender selectedRow];
    int isEnabled = [[sender selectedCell] intValue];
    pitchMode[whichCell] = isEnabled;
    if (isEnabled)
    	numPitchesEnabled++;
    else numPitchesEnabled--;
    return self;
}

static double ranNum()
    /* Returns a random number between 0 and 1. */
{
#   define   RANDOMMAX (double)((long)MAXINT)
    return ((double)random()) / RANDOMMAX;
 }

- compute:sender
{
#   define BASE_KEY_NUM 40
    id aScore,aNote,aPart;
    int i,j,k,l,keyNum;
    double x,time,rhythm;
     
    if (numPitchesEnabled == 0)
        return self;
    i=0;
    j=0;
    k=0;
    time = 0;
    aScore = [[Score alloc] init];
    aPart = [[Part alloc] init];
    [aPart addToScore:aScore];
    aNote = [[Note alloc] init];
    [aNote setPar:MK_tempo toDouble:tempo];
    [aScore setInfo:aNote];
    while(i<numEighthNotes || j<numSixteenthNotes || k<numQuarterNotes) {
	x = ranNum();
	if (x > .666) {
		if (i++>=numEighthNotes)
			continue;
		rhythm = 0.5;

	} else if (x > .333) {
		if (j++>=numSixteenthNotes)
			continue;
		rhythm = 0.25;
	} else { 
		if (k++>=numQuarterNotes)
			continue;
		rhythm = 1.0;
	}
	keyNum = -1;
	do {
		l = (int)(ranNum() * 11.999);
		if (pitchMode[l]) 
			keyNum = l + BASE_KEY_NUM;
	} while (keyNum == -1);
	aNote = [[Note alloc] init];
	[aNote setDur:rhythm];
	[aNote setTimeTag:time];
	time += rhythm;
	[aNote setPar:MK_keyNum toInt:keyNum];
	[aPart addNote:aNote];
    }
    aNote = [[Note alloc] init];
    [aNote setPar:MK_synthPatch toString:"Pluck"];
    [aPart setInfo:aNote];
    [aScore writeOptimizedScorefile:"/tmp/test.playscore"];
    [aScore free];
    return self;
}

- play:sender
{
    system("playscore -f -q /tmp/test.playscore");
    return self;
}


@end
