/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


//
// Include the needed Linux header files
//
#include <math.h>
#include <stdio.h>


//
// Calculate the inverse CIE-1931 lightness
//
// Based on https://jared.geek.nz/2013/feb/linear-led-pwm
//
static double cie1931(double l)
{
    l *= 100.0;
    if(l <= 8) return l / 902.3;

    return pow( (l + 16.0) / 116.0, 3.0 );
}


//
// Generate LUT
//
static void genCIELUT(int bitMax, int bitMul)
{
    const int max = pow(2, bitMax) - 1;
    const int mul = pow(2, bitMul) - 1;

    printf("\nextern CIE1931LVal PROGMEM CIE1931L_MSB%d_O%d[%d] = {\n    ", bitMax, bitMul, max + 1);
    for(int i = 0; i <= max; ++i) {
        printf( "%d", static_cast<int>( round( cie1931( static_cast<double>(i) / max ) * mul ) ) );
        if(i < max) printf(", ");
    }
    printf("\n};\n");
}


//
// The main program
//
int main(void)
{
    // Generate some CIE-1931-Lightness Look-Up-Tables
    genCIELUT(2, 3);
    genCIELUT(2, 4);
    genCIELUT(2, 5);
    genCIELUT(2, 6);
    genCIELUT(2, 7);
    genCIELUT(2, 8);

    genCIELUT(3, 5);
    genCIELUT(3, 6);
    genCIELUT(3, 7);
    genCIELUT(3, 8);

    genCIELUT(4, 7);
    genCIELUT(4, 8);

    genCIELUT(5, 8);

    printf("\n");

    return 0;
}
