<?php

echo "=== Format Information Analysis ===\n\n";

// ISO/IEC 18004 Specification:
// EC Level encoding in format info:
// L = 01
// M = 00
// Q = 11
// H = 10

// Current table entry for M, Pattern 2:
$currentFormatBits = 0b101111001111100;
$currentBinary = sprintf('%015b', $currentFormatBits);

echo "Current M, Pattern 2: {$currentBinary}\n";
echo "Bits breakdown:\n";
echo "  Bits 0-1 (EC): " . substr($currentBinary, 0, 2) . " = ";
$ecBits = substr($currentBinary, 0, 2);
echo match($ecBits) {
    '01' => 'L',
    '00' => 'M',
    '11' => 'Q',
    '10' => 'H',
    default => 'Unknown'
};
echo "\n";

echo "  Bits 2-4 (Mask): " . substr($currentBinary, 2, 3) . " = Pattern " . bindec(substr($currentBinary, 2, 3)) . "\n";
echo "  Bits 5-14 (BCH): " . substr($currentBinary, 5) . "\n\n";

// Reference: Correct format for M, Pattern 2 should start with 00010
echo "Expected for M, Pattern 2:\n";
echo "  EC Level M = 00\n";
echo "  Mask Pattern 2 = 010\n";
echo "  Combined (5 data bits) = 00010\n";
echo "  With BCH correction = 00010??????????  (10 BCH bits)\n\n";

// Check all M entries
echo "Checking all M entries in table:\n";
$tableM = [
    0 => 0b101010000010010,
    1 => 0b101000100100101,
    2 => 0b101111001111100,
    3 => 0b101101101001011,
    4 => 0b100010111111001,
    5 => 0b100000011001110,
    6 => 0b100111110010111,
    7 => 0b100101010100000,
];

foreach ($tableM as $mask => $formatBits) {
    $binary = sprintf('%015b', $formatBits);
    $ecBits = substr($binary, 0, 2);
    $maskBits = substr($binary, 2, 3);
    
    echo "Mask {$mask}: {$binary} ";
    echo "EC=" . match($ecBits) {
        '01' => 'L',
        '00' => 'M',
        '11' => 'Q',
        '10' => 'H'
    };
    echo " Mask={$maskBits}\n";
}
