/* For general info, see UWB-TaDa.rtf */

	// useful functions to have
(
q = q ? ();	// q is a Dictionary for storing things by name.

	// mac and linux only
q.localDir = Document.current.path.dirname; 
	// on win, put in the path where this textfile is
// 	q.localDir = "C:/Wherever/this/file/maybe";

// Array for 23 grid points
// with p_angle, p_delay, p_magn, 26 points for p_shape
q.readData = { |q, path|
	var lines = FileReader.read(path, true)
		.collect({ |line| line.select(_.size > 10) })
		.select(_.size > 10);

	var data = lines.collect(_.collect(_.asFloat));
	data.flop;
};

	// MTX writer for Pure Data
q.writeMtx = { |q, path, data|
	var file = File(path, "w"); 
	file.write("matrix" ++ Char.tab ++ "29" ++ Char.tab ++ "23" ++ Char.nl);
	data.flop.do({ |line| 
		line.do({ |x, i| file.write(x.asString); if( i<line.size,{ file.write(Char.tab) }) });
		file.write(Char.nl);
	});
	file.close;
};

		// make a window to show one frame of data. mac only.
q.makeWin = {	 
	q.pixsize = 3;
	q.win = SCWindow("UWB Propagation", Rect(0,0, 100 * q.pixsize, 100 * q.pixsize)).front;
	q.win.view.background_(Color.grey);
	q.win.drawHook = { 
		var black, white;
		q.frontFrame.do { |line| 
			var x,y;
			Color.grey(line[2]).set;
			x = line[0]/2pi*100;
			y = line[1]/70*100;
			Pen.addArc( (x * q.pixsize)@(y * q.pixsize), 3, 0, 2pi);
			Pen.fill;
		}
	};
	q.win.refresh;
};
q.makeWin;

q.toFront = { |q, frame| 
	q.frontFrame = frame;
	q.frontFrame[2].normalize;
	defer { try { q.win.refresh; } };
	frame;
};
)

// read in the data and display it 
(
q.data1 = q.readData(q.localDir ++ "/data01_ascii_b_9-3-06");
q.data2 = q.readData(q.localDir ++ "/data11_ascii_b_9-3-06");
q.toFront(q.data1);
q.data1.do({ |i| i[3..].plot});
)

// write MTX for Pd
q.writeMtx(q.localDir ++ "/data01.mtx", q.data1);
q.writeMtx(q.localDir ++ "/data02.mtx", q.data2);

/****** Sonification sketches: *****/

	// define dataset
q.data = q.data1;
	// Make envelopes and show them in plots
(
Tdef(\envs, {
	q.data.do({ |d| 
		{ Env.new(d[3..].pow(2).normalize, 0.1 ! 25, 'linear').test.plot }.defer;
		2.6.wait
	})
}).play;	
)
	// use the envelopes with white noise 
	// multiply with magnitude
	// place according incomming angle with stereo pan 
(
q.data.do({ |d, i|
	SynthDef("env" ++  i.asString, 
	{ 	Out.ar(0, Pan2.ar(EnvGen.kr(
			Env.new(d[3..].pow(2).normalize, 0.05 ! 25, 'linear'), 
				1.0, doneAction: 2) * 
			WhiteNoise.ar * (10.pow(4) * d[2]).postln), d[1] / 2pi - 1);
	}).send(s);
});

	// play them according to the delay
q.data.do({ |d, i|
	{ Synth("env" ++ i.asString); }.defer((d[0] * 2).postln);
});
)

	// load the shapes into buffers
q.shapeBuf = q.data.collect({ |b| 
	Buffer.loadCollection(s, b[3..].normalize(-1,1)).bufnum
});

p = ProxySpace.push;
ProxySynthDef.sampleAccurate_(true);