/*  SpiralSynth
 *  Copyleft (C) 2000 David Griffiths <dave@pawfal.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ 

#include "Delay.h"

static const int DELAYBUFFERSIZE=SpiralInfo::SAMPLERATE;


Delay::Delay() :
m_Write(0),
m_Delay(0.5),
m_Feedback(0.5)
{
	m_Buffer = new short[DELAYBUFFERSIZE];
}

Delay::~Delay()
{
	delete[] m_Buffer;
}

void Delay::GetOutput(short *data)
{
	int n=0;
	long Length=static_cast<long>(m_Delay*DELAYBUFFERSIZE);
	long temp=0;
	
	while (n<SpiralInfo::BUFSIZE)
	{
		temp=static_cast<long>(data[n]+m_Buffer[m_Write]*m_Feedback);

		if (temp>SpiralInfo::MAXSAMPLE) temp=SpiralInfo::MAXSAMPLE;
	 	if (temp<-SpiralInfo::MAXSAMPLE) temp=-SpiralInfo::MAXSAMPLE;

		m_Buffer[m_Write]=static_cast<short>(temp);

		data[n]=m_Buffer[m_Write];

		n++;
		m_Write++;
		if (m_Write>Length) m_Write=0;
	}
}

void Delay::Randomise()
{
	m_Delay=RandFloat();
	m_Feedback=RandFloat();
}


istream &operator>>(istream &s, Delay &o)
{
	s>>o.m_Delay>>o.m_Feedback;
	return s;
}

ostream &operator<<(ostream &s, Delay &o)
{
	s<<o.m_Delay<<" "<<o.m_Feedback<<" ";
	return s;
}
