#include <stdlib.h>

#include "mfsk.h"
#include "trx.h"
#include "fft.h"
#include "sfft.h"
#include "filter.h"
#include "interleave.h"
#include "viterbi.h"

static void mfsk_txinit(struct trx *trx)
{
	struct mfsk *m = (struct mfsk *) trx->modem;

	m->bitstate = 0;
	m->encstate = 0;
	m->txstate = STATE_PREAMBLE;
}

static void mfsk_rxinit(struct trx *trx)
{
}

static void mfsk_destructor(struct trx *trx)
{
	struct mfsk *m = (struct mfsk *) trx->modem;

	clear_fft(m->fft);
	clear_sfft(m->sfft);
	clear_filter(m->hilbert);
	clear_viterbi27(m->viterbi);

	free(m);

	trx->modem = NULL;

	trx->txinit = NULL;
	trx->rxinit = NULL;
	trx->txprocess = NULL;
	trx->rxprocess = NULL;
	trx->destructor = NULL;
}

void mfsk_init(struct trx *trx)
{
	struct mfsk *m;

	if ((m = calloc(1, sizeof(struct mfsk))) == NULL)
		return;

	m->fft = init_fft(SymbolLen);
	m->sfft = init_sfft(SymbolLen, BaseTone, BaseTone + NumTones);
	m->hilbert = init_filter(0.05, 0.45);
	m->viterbi = init_viterbi27();

	init_interleaver();
	init_deinterleaver();

	if (!m->fft || !m->sfft || !m->hilbert || !m->viterbi)
		return;

	trx->modem = m;

	trx->txinit = mfsk_txinit;
	trx->rxinit = mfsk_rxinit;

	trx->txprocess = mfsk_txprocess;
	trx->rxprocess = mfsk_rxprocess;

	trx->destructor = mfsk_destructor;

	trx->samplerate = SampleRate;
	trx->fragmentsize = SymbolLen;
	trx->bandwidth = (NumTones - 1) * ToneSpacing;
}
