/*  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 "Sequencer.h"

Sequencer::Sequencer() :
m_Playing(false),
m_Step(0),
m_NCalls(10),
m_Count(0),
m_ArpType(1),
m_Octave(3),
m_Length(15),
m_Arp(false),
m_ArpNotes(2),
m_ArpPos(0),
m_OffsetNote(0),
m_OffsetOct(0)
{
	for(int n=0; n<191; n++) m_EventList[n]=false; 
	for(int n=0; n<16; n++) m_TimeList[n]=0.5f;
	for(int n=0; n<12; n++) m_FreqList[n]=0.0f;
	for(int n=0; n<16; n++) m_VolList[n]=1.0f;
}

void Sequencer::Trigger(int oct, int note)
{
	m_OffsetOct=oct;
	m_OffsetNote=note;
}

bool Sequencer::GetSeqNote(float &note, int &oct, int &key)
{
	if (!m_Playing) return false;
	
	int Start=m_Step*12;
	bool e=false;
	m_Count++;
	if (m_Count>m_NCalls)
	{
		m_Count=0;
		// check current notes
		for (int n=0; n<12; n++)
		{
			// is an event sequenced?
			if (m_EventList[Start+n]==true)
			{
				e=true;
				oct=m_Octave+m_OffsetOct;
				key=n+m_OffsetNote;
				
cerr<<"Offset="<<m_OffsetOct<<" "<<m_OffsetNote<<endl;				
cerr<<"result="<<oct<<" "<<key<<endl;				

				if (oct<0) oct=0;
				if (oct>5) oct=5;
				if (key<0) key=0;
				if (key>11) key=11;				

				note=NoteTable[oct][key];				
			}
					
		}

		m_Step++;
		if (m_Step>m_Length) 
		{	
			m_Step=0;
			
			if (m_Arp) 
			{
				if (m_ArpType==1)
				{
					m_ArpPos++;
					if (m_ArpPos>m_ArpNotes) m_ArpPos=0;
				}
				else
				{
					m_ArpPos--;
					if (m_ArpPos<0) m_ArpPos=m_ArpNotes;
				}
			}
		}
	}
	return e;
}
