#include "../H/ugens.h"
#include "../H/sfheader.h"
#include "../objc/Delay.h"

int NBYTES = 32768;
extern SFHEADER sfdesc[NFILES];

id delayline;

/* a simple instrument which passes a two channel signal 
through a reverb, and delays and reverbs some of it (with
a time delay between speakers.  A nice way to gently and
cheaply put some gloss on a signal.  Note that it uses
a Delay object defined in the objc directory.  */

double reverbit(p,n_args)
float *p;
{
	int i,j,nsamps,input1,input2,output;
	float xin[4],out[4],amp1,amp2;
	float array[7500],xx,reverbtime,reverbpct;
	float samples[5000],yy,delaytime;
	int delvals[2],nchans;

	/* p0=start, p1=dur, p2=inskip, p3=reverbtime, p4=reverbpercent p5=rightchannel delay*/
	input1=0; output=1; 
	
	nsamps=setnote(p[0],p[1],output);  /* position outputfile*/
	setnote(p[2],p[1],input1);	   /* position inputfile1*/
	nchans = sfchans(&sfdesc[0]);
	reverbtime = p[3];
	reverbpct = p[4];
	delaytime = p[5];
	[delayline size:.1 sRate:SR];

	rvbset(reverbtime,0,array);

	for(i=0; i<nsamps; i++) {
		if(!GETIN(xin,input1))  break;  
		if(nchans == 1) xin[1] = xin[0];
		xx = -reverbpct * reverb(xin[0]+xin[1],array);
		/* flip phase of reverberated signal */
		[delayline put:xx];
		yy = [delayline get:delaytime];
		out[0] = xin[0] + xx;
		out[1] = xin[1] + yy;
		ADDOUT(out,output);
	}
	/* ring down reverb */
	nsamps = reverbtime * SR;
	for(i=0; i<=nsamps; i++) {
		xx = reverbpct * reverb(0.,array);
		[delayline put:xx];
		yy = [delayline get:delaytime];
		out[0] =  xx;
		out[1] =  yy;
		ADDOUT(out,output);
	}
	endnote(output);
}

profile()
{
	UG_INTRO("reverbit",reverbit);
	delayline = [Delay create];
}
