/* crudelooch -- simple RTcmix interface program
 * 
 *  uses the WAVETABLE instrument,
 *  based on the old "looching" application from NeXT machines
 *
 *  BGG
 *
 * NOTE:  this does not always shut down cleanly -- you may have to kill
 * the CMIX process running after halting this with CTRL-C
 *
*/

#include <stdio.h>

#include "../lib/RTsockfuncs.h"
#include "../lib/randfuncs.h"

int theSock;


main()
{
	char name[100];
	float start, dur, pval;
	int RTpid;
	float brrand(), rrand();

	float pitches[14] = {50.0, 66.667, 75.0, 100.0, 114.0, 133.333, 150.0, 177.777, 200.0, 228.0, 266.666, 300.0, 355.555, 400.0 };
	float sleepness;
	int i;
	float brrand(); /* returns a random # between 0 and 1 */


	/* start up the instrument */
	RTpid = RTopensocket(0, "CMIX");
	sleep(3); /* allow the process time to start */

	/* get name of server */
	printf("enter host name of server: ");
	scanf("%s",name);

	/* open up the socket */
	theSock = RTsock(name, 0);

	/* set up the instrument */
	RTsendsock("rtsetparams", theSock, 2, 22050.0, 2.0);
	RTsendsock("load", theSock, 1, "WAVETABLE");
	RTsendsock("makegen", theSock, 10, 1.0, 10.0, 1000.0, 1.0, 0.5, 0.25, 0.125, 0.06, 0.03, 0.015);
	RTsendsock("makegen", theSock, 8, 2.0, 7.0, 1000.0, 0.0, 500.0, 1.0, 500.0, 0.0);


	tsrand(); /* seeds the random generators with time-of-day */

	while(1) {
		for (i = 0; i < 4; i++) {
			if (brrand() < 0.5) {
				start = 1.0;
				dur = brrand() * 20.0 + 5.0;
				pval = pitches[(int)(brrand() * 14.0)];
				RTsendsock("WAVETABLE", theSock, 5, start, dur, 4000.0, pval, 0.0);
				start += brrand();
				dur += brrand();
				pval += rrand() * (pval * 0.0069);
				RTsendsock("WAVETABLE", theSock, 5, start, dur, 4000.0, pval, 1.0);
				start += brrand();
				dur += brrand();
				pval += rrand() * (pval * 0.0069);
				RTsendsock("WAVETABLE", theSock, 5, start, dur, 4000.0, pval, 0.2);
				start += brrand();
				dur += brrand();
				pval += rrand() * (pval * 0.0069);
				RTsendsock("WAVETABLE", theSock, 5, start, dur, 4000.0, pval, 0.8);
			}
		}
		sleepness = brrand() * 10.0 + 4.0;
		sleep((int)sleepness);
	}
}
