#include "SimDelay.h"

SimDelay::SimDelay() :
	delay(0, Stk::sampleRate()),
	wavOut(Stk::sampleRate() * 3)
	//wavOut("test.wav", 1, FileWrite::FILE_WAV, )
{
	sine.setFrequency(440);
	
	adsr.setAllTimes(0.01, 0.2, 0.2, 0.2); // A, D, S level, R time sec
	adsr.keyOn();
	
	delay.setDelay((unsigned long) (Stk::sampleRate() * 0.1)); // 0.1secj
	delay.tapIn(0.2, (unsigned long) (Stk::sampleRate() * 0.01)); // 0.1secj
	delay.tapIn(0.2, (unsigned long) (Stk::sampleRate() * 0.04)); // 0.1secj
	//delay.tapIn(0.2, 1000);

	//wavOut.openFile("test.wav", 1, FileWrite::FILE_WAV, Stk::STK_SINT16);
	wavOut.openFile("test.wav", 1, FileWrite::FILE_WAV, Stk::STK_FLOAT32);
}

SimDelay::~SimDelay()
{
	try {
		wavOut.closeFile();
	} catch(StkError error) {
		error.printMessage();
	}
}

StkFloat SimDelay::tick(void)
{
	lastSample = sine.tick() * adsr.tick();
	
	lastSample = delay.tick(lastSample);
	lastSample += delay.tapOut((unsigned long) (Stk::sampleRate() * 0.01)); // 0.1secj
	lastSample += delay.tapOut((unsigned long) (Stk::sampleRate() * 0.04)); // 0.1secj
	lastSample *= 0.2;

	//wavOut.tick((short)(lastSample * SHRT_MAX));
	wavOut.tick(lastSample);
	
	return lastSample;
}
