<?php
/* Generate minimum data bits per ECC level for tables `AztecDataSizes` & `AztecCompactDataSizes` in "aztec.h" */
/*
    libzint - the open source barcode library
    Copyright (C) 2026 Robin Stuart <rstuart114@gmail.com>
*/
/* SPDX-License-Identifier: BSD-3-Clause */

$percents = array(0.10, 0.23, 0.36, 0.50);

$full_sizes = array(
     21,  48,  60,  88, 120,  156, 196, 240,  230,  272,  316,  364,  416,  470,  528,  588,
    652, 720, 790, 864, 940, 1020, 920, 992, 1066, 1144, 1224, 1306, 1392, 1480, 1570, 1664
);

$compact_sizes = array(17, 40, 51, 76 /* 64 data blocks (Mode Message max) but 76 altogether */ );

function codeword_size($layers) {
    if ($layers <= 2) {
        return 6;
    }
    if ($layers <= 8) {
        return 8;
    }
    if ($layers <= 22) {
        return 10;
    }
    return 12;
}

function data_size($size, $bits, $percent) {
    $size_bits = $size * $bits;
    $ecc_bits = (int) ceil($size_bits * $percent);
    $ret = $size_bits - ($ecc_bits + 3 * $bits);
    return $ret;
}

function full_data_size($i, $j) {
    global $percents, $full_sizes;
    return data_size($full_sizes[$j], codeword_size($j + 1), $percents[$i]);
}

function compact_data_size($i, $j, &$msg) {
    global $percents, $compact_sizes;
    $msg = '';
    $bits = codeword_size($j + 1);
    $data_size = data_size($compact_sizes[$j], $bits, $percents[$i]);
    if ($data_size > 64 * $bits) {
        $data_size = 64 * $bits;
        $msg = ' /* Max 64 * 8 */';
    }
    return $data_size;
}

print <<<EOD
/* Tables `AztecDataSizes` and `AztecCompactDataSizes` generated by "backend/tools/gen_aztec_data_sizes.php" */
static const short AztecDataSizes[4][32] = { {

EOD;
for ($i = 0; $i < 4; $i++) {
    printf("        /* Data bits per symbol maximum with %d%% error correction */\n", (int) ($percents[$i] * 100));
    printf("        ");
    for ($j = 0; $j < 16; $j++) {
        printf($j <= 6 ? "%4d, " : ($j === 15 ? "%5d," : "%5d, "), full_data_size($i, $j));
    }
    printf("\n        ");
    for (; $j < 32; $j++) {
        printf($j <= 22 ? "%4d, " : ($j === 31 ? "%5d" : "%5d, "), full_data_size($i, $j));
    }
    printf($i === 3 ? "\n    }\n" : "\n    }, {\n");
}
printf("};\n");

print <<<EOD

static const short AztecCompactDataSizes[4][4] = { {

EOD;
for ($i = 0; $i < 4; $i++) {
    printf("        /* Data bits per symbol maximum with %d%% error correction */\n", (int) ($percents[$i] * 100));
    printf("        ");
    for ($j = 0; $j < 4; $j++) {
        $compact_data_size = compact_data_size($i, $j, $msg);
        printf($j === 3 ? "%d%s" : "%d%s, ", $compact_data_size, $msg);
    }
    printf($i === 3 ? "\n    }\n" : "\n    }, {\n");
}
printf("};\n");

/* vim: set ts=4 sw=4 et : */
