<?php

echo "=== Analyzing Horizontal Format Placement Issue ===\n\n";

// Our format for M, Mask 2
$ourFormat = 0b101111001111100;
$ourBinary = sprintf('%015b', $ourFormat);

// Python format for M, Mask 0  
$pythonFormat = 0b101010000010010;
$pythonBinary = sprintf('%015b', $pythonFormat);

echo "Our Format (M, Mask 2):    {$ourBinary}\n";
echo "Python Format (M, Mask 0): {$pythonBinary}\n\n";

echo "Python reads back horizontally: 101010000100100\n";
echo "This means positions 9,10,12,13 are swapped when READ\n\n";

echo "If we apply bit indices [0,1,2,3,4,5,6,7,8,10,9,11,13,12,14] when WRITING:\n";

$bitIndices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 9, 11, 13, 12, 14];
$output = '';

for ($i = 0; $i < 15; $i++) {
    $bitIndex = $bitIndices[$i];
    $bit = ($ourFormat >> (14 - $bitIndex)) & 1;
    $output .= $bit;
}

echo "We write: {$output}\n";
echo "Expected: 101111001111100 (vertical)\n";
echo "Match: " . ($output === $ourBinary ? "✅" : "❌") . "\n\n";

echo "The issue: We're SWAPPING when writing, but we should write SEQUENTIALLY!\n";
echo "The swap happens when READING, not writing.\n\n";

echo "Let's write sequentially:\n";
$output2 = '';
for ($i = 0; $i < 15; $i++) {
    $bit = ($ourFormat >> (14 - $i)) & 1;
    $output2 .= $bit;
}

echo "Sequential write: {$output2}\n";
echo "This should match vertical: " . ($output2 === $ourBinary ? "✅" : "❌") . "\n";

