// MIDI note handling
(
var midiIn, synths, activeNotes;

// Connect to MIDI
MIDIClient.init;
MIDIIn.connectAll;


// Note On: add num to activeNotes and set synth gate to 1
MIDIdef.noteOn(\noteOn, { |vel, num, chan, src|
    var freq = num.midicps;
	var index;

	//postln("Note On: " + num + " Velocity: " + vel);

    if (vel > 0) {

		// Find first available (nil) slot
		index = ~activeNotes.detectIndex({ |s| s.isNil });
        if (index.notNil) {
			~synths[index].set(\gate, 1);
			~synths[index].set(\freq, freq);
			~synths[index].set(\amp, vel/127);
            ~activeNotes[index] = num; // Map note to synth index
			~filterEnv.set(\gate, 1);  // Triggers the filter envelope
        } {
            "No available synth slots!".postln;
        }

    } { // Treat as noteOff if it is a noteOn with velocity 0
		index = ~activeNotes.detectIndex({ |s| (s == num) });
		if (index.notNil) {
			~activeNotes[index] = nil;
			~synths[index].set(\gate, 0);
			~filterEnv.set(\gate, 0); // Releases the filter envelope
		}
	}
});

// Note Off: set synth gate to 0 and remove num from activeNotes
MIDIdef.noteOff(\noteOff, { |vel, num, chan, src|
	var index;

	//postln("Note Off: " + num + " Velocity: " + vel);

	index = ~activeNotes.detectIndex({ |s| (s == num) });
	if (index.notNil) {
		~activeNotes[index] = nil;
		~synths[index].set(\gate, 0);
		~filterEnv.set(\gate, 0); // Releases the filter envelope
	}
});


// Run these functions directly
"MIDI functions loaded.".postln;
)

