<?php

declare(strict_types=1);

echo "=== Analyzing Data Placement Order ===\n\n";

$size = 21;

echo "Expected placement order according to ISO/IEC 18004:\n\n";

$order = 0;

for ($col = $size - 1; $col >= 1; $col -= 2) {
    if ($col === 6) {
        echo "Skip timing column 6\n";
        $col--;
    }

    // Calculate direction
    $upward = ((int) (($size - 1 - $col) / 2) % 2) === 0;
    $direction = $upward ? '⬆️ UP' : '⬇️ DOWN';

    echo "Columns {$col}-" . ($col - 1) . " ({$direction}):\n";

    for ($i = 0; $i < $size; $i++) {
        $row = $upward ? ($size - 1 - $i) : $i;

        for ($c = 0; $c < 2; $c++) {
            $currentCol = $col - $c;

            // Check if function pattern
            $isFunctionPattern = false;

            // Finder patterns + separators
            if (($row <= 8 && $currentCol <= 8) ||
                ($row <= 7 && $currentCol >= $size - 8) ||
                ($row >= $size - 8 && $currentCol <= 7)) {
                $isFunctionPattern = true;
            }

            // Timing patterns
            if ($row === 6 || $currentCol === 6) {
                $isFunctionPattern = true;
            }

            // Dark module
            if ($row === 13 && $currentCol === 8) {
                $isFunctionPattern = true;
            }

            // Format info
            if ($row === 8 || $currentCol === 8) {
                $isFunctionPattern = true;
            }

            if (!$isFunctionPattern) {
                if ($order < 20) {  // Only show first 20
                    echo sprintf("  [%3d] (%2d,%2d)\n", $order, $row, $currentCol);
                }
                $order++;
            }
        }
    }

    if ($order >= 20) {
        echo "  ... (showing first 20 positions)\n";
        break;
    }

    echo "\n";
}

echo "\nTotal data positions: {$order}\n";

// Now analyze what SHOULD be the placement according to ISO spec
echo "\n=== ISO/IEC 18004 Specification ===\n";
echo "Data placement starts at bottom-right corner\n";
echo "Moves in 2-column vertical stripes\n";
echo "Direction alternates: UP, DOWN, UP, DOWN, ...\n";
echo "\nFor Version 1 (21x21):\n";
echo "- Total modules: 21x21 = 441\n";
echo "- Function patterns: Finder(3x49) + Timing(2x15) + Format(31) + Dark(1) = 178 modules\n";
echo "- Data+EC modules: 441 - 178 = 263 modules\n";
echo "- Data+EC codewords: 16 + 10 = 26 bytes = 208 bits\n";
echo "- Padding modules: 263 - 208 = 55 light modules\n";
