<?php

echo "=== Reverse Engineering Exact Bit Mapping ===\n\n";

// Python M, Mask 0 reference
$formatBits = 0b101010000010010;
$formatBinary = sprintf('%015b', $formatBits);

$pythonH = "101010000100100";
$pythonV = "101010000010010";

echo "Format Bits: {$formatBinary}\n";
echo "Python H:    {$pythonH}\n";
echo "Python V:    {$pythonV}\n\n";

// Find the exact mapping for horizontal
echo "=== Horizontal Bit Mapping ===\n";
echo "Reading Pos | Column | Should Be | Actual Bit | Comes From Format Bit\n";

$hCols = [0, 1, 2, 3, 4, 5, 7, 8, 20, 19, 18, 17, 16, 15, 14];

for ($i = 0; $i < 15; $i++) {
    $col = $hCols[$i];
    $actualBit = $pythonH[$i];
    
    // Find which format bit this matches
    $matchedBitIndex = -1;
    for ($j = 0; $j < 15; $j++) {
        if ($formatBinary[$j] === $actualBit) {
            // Check if this makes sense
            if ($i < 8 && $j == $i) {
                $matchedBitIndex = $j;
                break;
            } elseif ($i >= 8) {
                $matchedBitIndex = $j;
            }
        }
    }
    
    // Actually, just check each position manually
    $expectedFormatBit = $formatBinary[$i];
    $match = $actualBit === $expectedFormatBit ? '✅' : '❌';
    
    if ($match === '❌') {
        // Find what it should be
        for ($j = 0; $j < 15; $j++) {
            if ($formatBinary[$j] === $actualBit) {
                echo sprintf("%11d | %6d | %9s | %10s | Bit %d %s\n", 
                    $i, $col, $expectedFormatBit, $actualBit, $j, $match);
                break;
            }
        }
    } else {
        echo sprintf("%11d | %6d | %9s | %10s | Bit %d %s\n", 
            $i, $col, $expectedFormatBit, $actualBit, $i, $match);
    }
}

echo "\n=== Conclusion ===\n";
echo "Positions that need swapping in horizontal:\n";
echo "Reading pos 9 (col 19): Use bit 10 instead of bit 9\n";
echo "Reading pos 10 (col 18): Use bit 9 instead of bit 10\n";
echo "Reading pos 12 (col 16): Use bit 13 instead of bit 12\n";
echo "Reading pos 13 (col 15): Use bit 12 instead of bit 13\n";
