#include "markov.h"

#include "ofMain.h"



Markov::Markov()
{
	
}

Markov::~Markov()
{
	delete []states;
	for(int i = 0; i < numstates; i++)	{
		delete []table[i];
	}
	delete []table;
}



void Markov::setup(int nstates)
{
	numstates = nstates;
	states = new MarkovState[numstates];
	table = new int*[numstates];
	
	for(int i = 0; i < numstates; i++)	{
		states[i].id=i;
		table[i] = new int[numstates];
	}
}

void Markov::update()
{
	
}

void Markov::setTransition(int state, int nextstate, int weight)
{
	table[state][nextstate] = weight;
}

int Markov::nextEvent(int inputState) 
{
	int targetSum   = 0;
	int sum         = 0;
	int outputState  = 0;
	int totalevents = 0;
	int i;

	inputState = inputState % numstates;  // remove any octave value
	
	for (i=0; i<numstates; i++) {
		totalevents += table[inputState][i];
	}
	
	targetSum   = (int)(ofRandomuf() * totalevents + 0.5);
	while (outputState < numstates && sum+table[inputState][outputState] < targetSum) {
		sum += table[inputState][outputState];
		outputState++;
	}

	return outputState;
}


