//quick network music introduction, from the network music session led by Julian in the summer school

//this sets up connections to the various IP addresses around the network- you will need to update this code to reflect your local setup 
(
a = [82, 87, 81, 90, 91, 83, 89, 92, 95, 42, 86, 88, 96].collect({ arg el;
	Server("test"++el, NetAddr("10.10.10." ++ el, 57110))
});
)

//makes a Server GUI that represents a particular network target
a[0].makeWindow;

//function to encapsulate sending a SynthDef to all Servers 
f = { arg synthDef; a.do({ arg el; synthDef.send(el) }) };

//send to a specific Server
(
SynthDef("finesine", { arg out, freq=440, amp=0.1, pan, sustain=0.01, x=0.5;
		var e, u;
		e = EnvGen.ar(Env.perc(0.001, sustain, amp), doneAction:2);
		u = SinOsc.ar(freq * [1.0, 5/6, 17/8] * XLine.ar(1 + x, 1, sustain)).sum * amp;
		Out.ar(out, u)
}).send(a[0]);
)

//use function f to send to all
(
f.value(
	SynthDef("finesine", { arg out, freq=440, amp=0.1, pan, sustain=0.01, x=0.5;
		var e, u;
		e = EnvGen.ar(Env.perc(0.001, sustain, amp), doneAction:2);
		u = SinOsc.ar(freq * [1.0, 5/6, 17/8] * XLine.ar(1 + x, 1, sustain)).sum * amp;
		Out.ar(out, u)
	})
)
)

//automate Synth grain firing once around the Servers in random order
(
Tdef(\x, {
	a.scramble.do { arg el, i;
		Synth.grain(\finesine, [\freq, 1000 *( i % 4).postln + 1000], el);
		0.1.wait;
	}
}).play;
)

//Using a pattern to target particular Servers in the array a
(
Tdef(\x, {
	var pat;
	pat = Pseq([0, 3, 1, 0, 0, 0, 0, 0]);
	pat.asStream.do { arg serverIndex, i;
		Synth.grain(\finesine, [\freq, 1000 *(serverIndex).postln + 1000], a[serverIndex]);
		0.1.wait;
	}
}).play;
)