#!/usr/local/bin/php
<?php

require "brainphuck/brainphuck.php";

if (!
$argv[1]) {

    echo 
"usage: ".basename($argv[0])." [options] filename.b\n\n";
    echo 
"  -o    output file name\n";
    echo 
"  -t    binary output target format\n";
    echo 
"            com  : 16 bit windows/dos .com binary\n";
    echo 
"            aout : 32 bit linux a.out binary\n";
    echo 
"  -Os   optimize for size (equivalent to -a1)\n";
    echo 
"  -Op   optimize for performance (equivalent to -a16)\n";
    echo 
"  -a    align jumps to N bytes\n";
    echo 
"  -s    strict parsing mode (ignore # and ! BF extensions)\n";
    echo 
"  -V    print version number and exit\n";

    die(
"\n");

}

$filename $argv[$argc 1];
$options getopt("t:a:o:O:sV");

isset(
$options["V"]) && die(BrainPhuck::VERSION."\n");

switch (
$options["t"]) {

    case 
"com":    $target BrainPhuck::COMPILE_COM;    break;
    case 
"aout":    $target BrainPhuck::COMPILE_AOUT;    break;

    default:    
$target strpos(PHP_OS"Linux") !== false BrainPhuck::COMPILE_AOUT BrainPhuck::COMPILE_COM;    break;

}

$align 4;

switch (
$options["O"]) {

    case 
"0":
    
$opt BrainPhuck::OPTIMIZE_NONE;
    break;

    case 
"1":
    
$opt BrainPhuck::OPTIMIZE_ZERO;
    break;

    case 
"2":
    
$opt BrainPhuck::OPTIMIZE_SETV;
    break;

    case 
"s":
    
$align 1;
    
$opt BrainPhuck::OPTIMIZE_ALL;
    break;

    case 
"p":
    
$align 16;
    
$opt BrainPhuck::OPTIMIZE_ALL;
    break;

    default:
    
$opt BrainPhuck::OPTIMIZE_DEFAULT;
    break;

}

if (
is_numeric($options["a"])) $align = (int)$options["a"];

if (isset(
$options["o"])) {

    
$outname $options["o"];

} else {

    
$outname strtok(basename($filename), ".") . (($target == BrainPhuck::COMPILE_COM) ? ".com" "");

}

$strict = isset($options["s"]);

$targets = array(BrainPhuck::COMPILE_COM => "16 bit windows/dos"BrainPhuck::COMPILE_AOUT => "32 bit linux");

echo 
"source    : {$filename}\n";
echo 
"output    : {$outname}\n";
echo 
"target    : {$targets[$target]} (align = " $align " bytes, opt = " $opt ")\n";

try {

    
$bf = new BrainPhuck();
    
$bf->Load_File($filename$strict BrainPhuck::PARSE_STRICT BrainPhuck::PARSE_EXT);
    
$bf->Optimize($opt);
    
    
$binary $bf->Compile($target$align);

    
file_put_contents($outname$binary);

    
chmod($outname0755);

    echo 
"size      : ".number_format(filesize($outname))." bytes\n";
    echo 
"\n";

} catch (
Exception $e) {

    die(
"error: ".$e->getMessage()."\n");

}

?>