<?php 

class CommandLine
{
    public static $args;
    
    public static function parseArgs($argv)
    {
        array_shift($argv);
        $out = array();
        foreach ($argv as $arg)
        {
            if (substr($arg, 0, 2) === '--')
            {
                $eqPos = strpos($arg, '=');
                if ($eqPos === false)
                {
                    $key = substr($arg, 2);
                    $value = isset($out[$key]) ? $out[$key] : true;
                    $out[$key] = $value;
                }
                else
                {
                    $key = substr($arg, 2, $eqPos - 2);
                    $value = substr($arg, $eqPos + 1);
                    $out[$key] = $value;
                }
            }
            else if (substr($arg, 0, 1) === '-')
            {
                if (substr($arg, 2, 1) === '=')
                {
                    $key = substr($arg, 1, 1);
                    $value = substr($arg, 3);
                    $out[$key] = $value;
                }
                else
                {
                    $chars = str_split(substr($arg, 1));
                    foreach ($chars as $char)
                    {
                        $key = $char;
                        $value = isset($out[$key]) ? $out[$key] : true;
                        $out[$key] = $value;
                    }
                }
            }
            else
            {
                $value = $arg;
                $out[] = $value;
            }
        }
        self::$args = $out;
        return $out;
    }
    
    public static function getBoolean($key, $default = false)
    {
        if (!isset(self::$args[$key]))
        {
            return $default;
        }
        $value = self::$args[$key];
        if (is_bool($value))
        {
            return $value;
        }
        if (is_int($value))
        {
            return (bool) $value;
        }
        if (is_string($value))
        {
            $value = strtolower($value);
            $map   = array(
                'y' => true,
                'n' => false,
                'yes' => true,
                'no' => false,
                'true' => true,
                'false' => false,
                '1' => true,
                '0' => false,
                'on' => true,
                'off' => false
            );
            if (isset($map[$value]))
            {
                return $map[$value];
            }
        }
        return $default;
    }
}

?>