// MIDI Input

(
SynthDef("testmidi", { arg freq=400, rf=800, amp=0.2;
	var sig, filt;
	sig = Saw.ar(freq*[0.997, 1.004], amp);
	filt = RLPF.ar(sig, rf, 0.1);
	Out.ar(0, filt);
	}, [0.1, 0.1, 0.1]).send(s);
)	

y = Synth.new("testmidi");
y.set(\amp, 0.01);
y.free

// MIDIClient.init

// MIDIIn.connect

(
var ins;
MIDIClient.init(8,8);	
ins = MIDIClient.sources.size;	
ins.do({ arg i;  MIDIIn.connect(i, MIDIClient.sources.at(i));
	});
)

MIDIIn.control = { arg src, chan, num, val; [chan, num, val].postln };

(
MIDIIn.control = { arg src, chan, num, val; 
	[chan, num, val].postln; 
	if(num == 81) { y.set(\freq, val / 127 * 1000 + 100 ) }; 
	};
)	

y = Synth.new("testmidi");

(
MIDIIn.control = { arg src, chan, num, val; 
	[chan, num, val].postln; 
	switch ( num )
		{ 81 }  { y.set(\freq, (val / 127 * 80).midicps ) } 
		{ 82 }  { y.set(\rf, val / 127 * 2000 + 100 ) } 
		{ 83 }  { y.set(\amp, (val * 0.5 - 60).dbamp  ) } 
		{ 65 } 	 { y.run( val == 127 ) }
		};
)	

// MIDI Output

MIDIClient.init(8,8);

m = MIDIOut(0, MIDIClient.destinations.at(0).uid);
m.noteOn(0, 67, 60);
m.noteOn(0, 67, 00);
m.allNotesOff(0)

(
e = Pbind(
	\type, \midi,
	\midiout, m,
	\tempo, 130 * 1/60/4,
	\dur, Pfunc({ coin(0.9).if(1/16, 1/2) }),
	\midinote, Pxrand( (40, 45 .. 75), inf),
	\bend, 64,
	\legato, 1.0,
	\amp, 0.7
	).play;
)

e.stop;

(
e = Pbind(
	\type, \midi,
	\midiout, m,
	\tempo, 130 * 1/60/4,
	\dur, 1.0,
	\strum, 0.015,
	\midinote, Pseq( [[ 40, 45, 50, 55, 59, 64]], inf),
	\bend, 64,
	\legato, 0.2,
	\amp, 0.7
	).play;
)

(
var chords, chordpattern, basic, dict;

chords = [[0,5,5,5,4,5].integrate+45, [0,5,5,4,5,5].integrate+44, 
		[0,5,4,5,5,5].integrate+43, [0,4,5,5,5,5].integrate+42, [0,5,5,5,5,4].integrate+41   ];
chordpattern = Pwalk( chords.collect {arg c; Pseq([c, c.reverse], 1)}, 1, 1).asStream;

basic = Pbind(	
	\type, \midi,
	\midiout, m,
	\tempo, 130 * 1/60/4,
	\bend, 64,
	\amp, 0.7
);

dict = (
	s: Pbindf(basic, 
		[\dur, \strum], Prand( [ Pseq([ [0.1,0.015], [1, 0.015]], 1),  Pseq([ [1.2 ,0.05]], 1) ], inf), 
		\legato, 0.2, 
		\midinote, Pfin(2, Pfunc({ chordpattern.next + 5 }))
		),
	b: Paddp(\midinote, Pbrown(0,5,3,1), 
		Pbindf(basic, 
		\dur, Pfunc({ coin(0.95).if(1/16, 1/2) }), 
		\midinote, Pn(Pxrand( (40, 45 .. 70) ++ (44, 48 .. 70), 3 ), {rrand(2,7)}) )
		),	
	c: Pbindf(basic, 
		\dur, 1/20, 
		\legato, 0.1, 
		\amp, Pseq([0.8, Pn(0.4, {rrand(2,7)})], inf), 
		\midinote, Pstutter(Prand([1,2,3,5,7],3), Pbrown( 70, 82, 3, 3)) )
	);

x = Pdict(dict, 
		Pxrand([\s, \b, \c], inf)
	).play;
)