#include <stdint.h>
#include <stdio.h>

#include "sigma_loader.h"
#include "sigma_program.h"

#define ADAU1761_DSP_RUN_REG   0x40F6
#define SIGMA_PROGRAM_BASE     0x0800
#define SIGMA_GAIN_ADDR        8

static int sigma_stop_dsp(audio_codec *codec)
{
    uint8_t v = 0x00;
    codec->writeCodecBytes(ADAU1761_DSP_RUN_REG, &v, 1);
    return 0;
}

static int sigma_start_dsp(audio_codec *codec)
{
    uint8_t v = 0x01;
    codec->writeCodecBytes(ADAU1761_DSP_RUN_REG, &v, 1);
    return 0;
}

static int sigma_load_program(audio_codec *codec)
{
    for (int i = 0; i < SIGMA_PROGRAM_WORDS; i++)
    {
        codec->writeCodecBytes(SIGMA_PROGRAM_BASE + i, sigma_program[i], 5);
    }

    return 0;
}

int sigma_set_gain_mute(audio_codec *codec)
{
    uint8_t gain[4] = {0x00, 0x00, 0x00, 0x00};   // Gain = 0
    codec->writeCodecBytes(SIGMA_GAIN_ADDR, gain, 4);
    return 0;
}

int sigma_set_gain_normal(audio_codec *codec)
{
    uint8_t gain[4] = {0x00, 0x80, 0x00, 0x00};   // Gain = 1.0
    codec->writeCodecBytes(SIGMA_GAIN_ADDR, gain, 4);
    return 0;
}

int sigma_set_gain_half(audio_codec *codec)
{
    uint8_t gain[4] = {0x00, 0x40, 0x00, 0x00};   // Gain = 0.5
    codec->writeCodecBytes(SIGMA_GAIN_ADDR, gain, 4);
    return 0;
}

int sigma_load_gain0_program(audio_codec *codec)
{
    sigma_stop_dsp(codec);
    sigma_load_program(codec);
    sigma_set_gain_mute(codec);
    sigma_start_dsp(codec);

    printf("SigmaStudio Gain=0 program loaded\n");
    return 0;
}