#!/usr/bin/perl -w
# ############################################################################
# (c) Copyright Virata Limited 2001
#
# Virata Limited Confidential and Proprietary
#
# The following software shell script ("Software") is strictly confidential and
# is proprietary to Virata Limited ("Virata").  It may only be read, used,
# copied, adapted, modified or otherwise dealt with by you if you have
# entered into a confidentiality agreement with Virata and then subject to the
# terms of that confidentiality agreement and any other applicable agreement
# between you and Virata.  If you are in any doubt as to whether you are
# entitled to access, read, use, copy, adapt, modify or otherwise deal with
# the Software or whether you are entitled to disclose the Software to any
# other person you should contact Virata.  If you have not entered into a
# confidentiality agreement with Virata granting access to this Software you
# should forthwith return all media, copies and printed listings containing
# the Software to Virata.
#
# Virata reserves the right to take legal action against you should you breach
# the above provisions.
#
# If you are unsure, or to report violations, please contact
# support@virata.com
# ############################################################################

#  cli_parser - XML CLI specification to C translator

my $version = "1.13";

# The variable below defines the minimum version which the templates
# file should require - if it requires a version lower than this, it is
# assumed to be an older version than is supported by this script, and
# a warning will be generated.
my $required_templates_version = "1.07";

require 5.004;
use strict;
use English;
use File::Basename;
use Config;

my $extra_lib_fix;
my $instbase;

BEGIN
{
    $extra_lib_fix = '';

    # Workaround Perl 5.004_4 dynaloader bug which looks in the wrong arch
    # directory (it looks in arch/perl_ver_including_patch_level,
    # Make maker puts the files in arch_perl_ver_without_patch_level)

    # lgd - 17/7/01 you also need this fix for perl 5.005 as well. *BUT* if
    # if you have it turned on for perl 5.6 it breaks on Windows (because
    # $arch_path contains an escape (c:\). Perl 5.6 on Windows seems not to
    # need this.

    if ( $] < 5.006 ) {
        my $arch_path = $Config{archlib};
        my $arch_base_path = dirname( dirname ( $arch_path ) );
        $arch_path =~ s/$arch_base_path//;
        $extra_lib_fix = $arch_path;
    }

    my $pathsep = ':';
    $pathsep = ';' if ( $^O =~ m/Win/ );

    my $PATH = $ENV{PATH};
    my @path = split(/[$pathsep]/,$PATH);
    foreach my $p (@path) {
        if ( $p =~ m/virata[\\\/]tools_[^\/]*[\\\/][^\/]+[\\\/]bin/ ) {
            $instbase = $p;
            last;
        }
    }
    die "Could not find Virata tools in path $PATH\n" unless $instbase;
    # df - The latest version of cygwin returns a different (wrong path)
    if ($instbase =~ /cygdrive/i)
    {
        $instbase =~ s/\/cygdrive\/c/$ENV{VIRATA_TOOLS_DRIVE}:/i;
 #       print "cli-parser in condition, df- instbase =  $instbase\n";
    }



    # Fix for perl 5.005_3 - this has to be in the BEGIN section as some
    # versions of Perl seem to find $Config{version} undefined
    if (defined $Config{version})
    {
        push @INC, $instbase . "/../lib/perl/lib/" . $Config{version};
    }
}

# Fix for perl 5.004_4
use lib dirname($instbase) . "/lib/perl/lib" . $extra_lib_fix;

# Fix for perl 5.004_5
use lib $instbase . "/../lib/perl/lib/" . $extra_lib_fix . "/auto/XML/Parser/Expat";

# For normal operation
use lib dirname($instbase) . "/lib/perl/lib";
use lib dirname($instbase) . "/lib/perl";

# Used when we execute cli_parser using ./cli_parser
use lib $instbase . "/../lib/perl/lib/" . $extra_lib_fix;
use lib $instbase . "/../lib/perl/lib";



use XML::Node;
use Getopt::Long;
use Data::Dumper;
use TreeNode;

my $warnings = 0;

# Handle warnings - currently this just counts warnings so the script can
# halt if there were any warnings parsing the XML, but could feasibly have
# it's operation changed by command-line options. Possibilities include the
# ability to ignore or even not output warnings, turning all warnings into
# fatal errors and logging warnings to a file.

local $SIG{__WARN__} = sub {

# When we reuse a parse node, the parse seems to complain that some subroutines
# are being redefined, so we filter those off and ignore them. To avoid this
# we'd have to define a new parse node for every file we parse - that doesn't
# seem to be a much better solution.

    unless ($_[0] =~ /^Subroutine handle/)
    {
        $warnings++;
        warn "WARNING: ".$_[0]
    }
};

my $progName = basename $0;

my $cliSpecNode = XML::Node->new();
my $templatesNode = XML::Node->new();

#### Handle command-line options
#
# Default command-line options
#

my $defaultTemplatesFile = "../../../source/webserver/atmos/cli/templates.xml";
my $defaultOutputFile = "parse_tree";
my $outputFile = $defaultOutputFile;
my $showVersion;
my $verbose = 0;
my $writeOutputFile = 1;
my $displayHelp = 0;
my $quiet = 0;
my $indentStep = 4;
my $templatesFile = $defaultTemplatesFile;

#
# Parse command-line options, overriding defaults above
#

my $res = GetOptions("quiet" => \$quiet,
                     "version" => \$showVersion,
                     "output=s" => \$outputFile,
                     "debug:i" => \$verbose,
                     "writeoutput!" => \$writeOutputFile,
                     "help" => \$displayHelp,
                     "templates:s" => \$templatesFile);

#
# The remaining arguments must be the CLI spec and (optionally) the templates
# file - check if they've been supplied (we'll check if they exist later)
#

my $cliSpec = $ARGV[0];

# If the CLI spec file hasn't been supplied, die with usage summary
if ( defined $showVersion ) {
    print "$progName version $version\n";
    exit 0;
}

unless (defined $cliSpec or $displayHelp or $showVersion)
{
    print "$progName: Must specify an argument\n";
    $displayHelp = 1;
}

unless ($verbose)
{
    $verbose = 0;
}

if ($verbose < 0)
{
    print "$progName: Argument to --verbose must be positive\n";
    $displayHelp = 1;
}

#
# Print command-line help and/or version and quit, if requested
#

if ($showVersion or $displayHelp or not $res)
{
    print "XML CLI spec to C code translator, version ".$version."\n";
    if ($displayHelp or not $res)
    {
        print <<EOF;
Parses an XML CLI specification file, passed in as an argument, and
generates from it a C source file. This file can be compiled and linked
into an ISOS build to implement the CLI specified. It contains functions to
build the parse tree(s) and also contains a list of action functions which
are used by the CLI parser.\n

Usage: $progName [ options ] <cli spec>\n

Arguments:
  <cli spec>       - XML CLI specification

Options:
  --output <f>     - Write out C++ file <f>.cc and header <f>.h
                     (default: ".$defaultOutputFile."(.cc|.h))
  --templates <f>  - Take code templates from XML file <f>
                     (default: ".$defaultTemplatesFile.")
  --nowriteoutput  - Do not actually write output file (for testing)
  --debug        - Be verbose - optionally supply an integer greater than
                     one for more verbosity
  --quiet          - Equivalent to --verbose 0, overrides --verbose
  --version        - Print current version number and exit
  --help           - Display this summary and exit
EOF
    }

    exit;
}

if ($quiet)
{
    $verbose = 0;
} else
{
    print "\n" if ($verbose == 1);
}

#
# Before we go any further, read in User.h file and extract access level
# names - if it doesn't exist, we die
#

undef $/;
open USER, "../../../source/im/shared/User.cc" or die "Could not open file ../../../source/im/shared/User.cc";
my $userCFile = <USER>;
close USER;

my %usernames = ();
my @usernamearray = ();
my $num = 0;

$userCFile =~ s/^.*AccessEnumStrings\s*\[\]\s*=\s*\{([^\}]*)\}.*$/$1/s;
while ($userCFile =~ /\"([^\"]*)\"/)
{
    $usernames{$1} = $num++;
    push @usernamearray, $1;
    $userCFile = $';
}

open USER, "../../../source/im/interfaces/im/ImUser.h" or die "Could not open file ../../../source/im/interfaces/im/ImUser.h";
$userCFile = <USER>;
close USER;
$/ = '\n';

my %userlevels = ();
$num = 0;

$userCFile =~ s/^.*enum\s*AccessEnum\s*\{\s*([^\}]*)\}.*$/$1/s;
$userCFile = ",".$userCFile;
while ($userCFile =~ /,\s*([^,\s]*)\s*/)
{
    $userlevels{$usernamearray[$num++]} = $1;
    $userCFile = $';
}

#### Register XML tags we're interested in with the XML parser
#
# NB - The functions used in parsing the file are at the end of this script
#
# First we list the variables directly written by the XML parser for the CLI
# spec
#

my $keyword_id = "";
my $keyword_type = "";
my $user = "";
my $param_name = "";
my $param_value = "";
my $action_id = "";
my $command_syntax = "";
my $node_id = "";
my $node_summary = "";
my $extra_args = "";
my $required_version = "";
my $extra_headers = "";
my $alias_from = "";
my $alias_to = "";
#
# Now the arrays and hashes used in the functions registered below
#

my %keywords = (); # stores keyword types indexed by id string
my @users = ();    # stores all the users allowed to use a command
my %params = ();   # stores parameter values indexed by name
my @actions = ();  # stores a ref to a hash with param list and action id
my %nodes;
my %aliases;

#
# tree_roots is a hash of roots of parse trees for each user
#

my %tree_roots = ();
my %action_functions = ();

#
# And the variables used for parsing the templates file
#

my $startFile = "";
my $startActionFunction = "";
my $startActionFunctionCheckArgs = "";
my $startActionFunctionCodeOnly = "";
my $startActionFunctionCheckArgsCodeOnly = "";
my $setFixedParam = "";
my $setVariableParam = "";
my $startActionCall = "";
my $endFixedParams = "";
my $endActionCall = "";
my $endFirstActionCall = "";
my $endActionCallSingle = "";
my $endActionFunction = "";
my $endActionFunctionCodeOnly = "";
my $declareParseTree = "";
my $startGenerateFunction = "";
my $addNode = "";
my $addRootNode = "";
my $addChildOfRoot = "";
my $stepBack = "";
my $endGenerateFunction = "";
my $startHeaderFile = "";
my $extraHeaders = "";
my $headerDeclareParseTree = "";
my $endHeaderFile = "";
my $startMenuSelectFunction = "";
my $checkMenu = "";
my $endMenuSelectFunction = "";
my $startTreeDeclaration = "";
my $endTreeDeclaration = "";
my $commandCode = '';
my $startAliasList = '';
my $aliasListEntry = '';
my $endAliasList = '';

#
# Now we build the CLI spec node tree
#

$cliSpecNode->register(">clispec>scriptversion", "char" => \$required_version);
$cliSpecNode->register(">clispec>scriptversion", "end" => \&handleVersion);
$cliSpecNode->register(">clispec>extraheaders", "char" => \$extra_headers);
$cliSpecNode->register(">clispec>extraheaders", "end" => \&handleExtraHeaders);
$cliSpecNode->register(">clispec>alias:from", "attr" => \$alias_from);
$cliSpecNode->register(">clispec>alias:to", "attr" => \$alias_to);
$cliSpecNode->register(">clispec>alias", "end" => \&handleAlias);
$cliSpecNode->register(">clispec>keyword:id", "attr" => \$keyword_id);
$cliSpecNode->register(">clispec>keyword:type", "attr" => \$keyword_type);
$cliSpecNode->register(">clispec>keyword", "end" => \&handleKeyword);
$cliSpecNode->register(">clispec>command:extraargs", "attr" => \$extra_args);
$cliSpecNode->register(">clispec>command>syntax", "char" => \$command_syntax);
$cliSpecNode->register(">clispec>command>user", "char" => \$user);
$cliSpecNode->register(">clispec>command>user", "end" => \&handleUser);
$cliSpecNode->register(">clispec>command>action:id", "attr" => \$action_id);
$cliSpecNode->register(">clispec>command>action>param:name", "attr" => \$param_name);
$cliSpecNode->register(">clispec>command>action>param:value", "attr" => \$param_value);
$cliSpecNode->register(">clispec>command>action>param", "end" => \&handleParam);
$cliSpecNode->register(">clispec>command>action", "end" => \&handleAction);
$cliSpecNode->register(">clispec>command", "end" => \&handleCommand);
$cliSpecNode->register(">clispec>node:id", "attr" => \$node_id);
$cliSpecNode->register(">clispec>node>summary", "char" => \$node_summary);
$cliSpecNode->register(">clispec>node", "end" => \&handleNode);

#
# support for the "c=" argument, as in:
# <command>
#     <syntax>my func</syntax>
#     <user>default</user>
#     <code>myFunc();</code>
# </command>
#
$cliSpecNode->register(">clispec>command>code", "char" => \$commandCode);
$cliSpecNode->register(">clispec>command>code", "end" => \&handleCode);


#
# Now the template ones
#

$templatesNode->register(">clitemplates>scriptversion", "char" => \$required_version);
$templatesNode->register(">clitemplates>scriptversion", "end" => \&handleVersion);
$templatesNode->register(">clitemplates>startfile", "char" => \$startFile);
$templatesNode->register(">clitemplates>startactionfunction", "char" => \$startActionFunction);
$templatesNode->register(">clitemplates>startactionfunctioncheckargs", "char" => \$startActionFunctionCheckArgs);
$templatesNode->register(">clitemplates>startactionfunctioncodeonly", "char" => \$startActionFunctionCodeOnly);
$templatesNode->register(">clitemplates>startactionfunctioncheckargscodeonly", "char" => \$startActionFunctionCheckArgsCodeOnly);
$templatesNode->register(">clitemplates>setfixedparam", "char" => \$setFixedParam);
$templatesNode->register(">clitemplates>setvariableparam", "char" => \$setVariableParam);
$templatesNode->register(">clitemplates>startactioncall", "char" => \$startActionCall);
$templatesNode->register(">clitemplates>endfixedparams", "char" => \$endFixedParams);
$templatesNode->register(">clitemplates>endactioncall", "char" => \$endActionCall);
$templatesNode->register(">clitemplates>endfirstactioncall", "char" => \$endFirstActionCall);
$templatesNode->register(">clitemplates>endactioncallsingle", "char" => \$endActionCallSingle);
$templatesNode->register(">clitemplates>endactionfunction", "char" => \$endActionFunction);
$templatesNode->register(">clitemplates>endactionfunctioncodeonly", "char" => \$endActionFunctionCodeOnly);
$templatesNode->register(">clitemplates>declareparsetree", "char" => \$declareParseTree);
$templatesNode->register(">clitemplates>starttreedeclaration", "char" => \$startTreeDeclaration);
$templatesNode->register(">clitemplates>endtreedeclaration", "char" => \$endTreeDeclaration);
$templatesNode->register(">clitemplates>startgeneratefunction", "char" => \$startGenerateFunction);
$templatesNode->register(">clitemplates>addnode", "char" => \$addNode);
$templatesNode->register(">clitemplates>addrootnode", "char" => \$addRootNode);
$templatesNode->register(">clitemplates>addchildofroot", "char" => \$addChildOfRoot);
$templatesNode->register(">clitemplates>endgeneratefunction", "char" => \$endGenerateFunction);
$templatesNode->register(">clitemplates>stepback", "char" => \$stepBack);
$templatesNode->register(">clitemplates>startmenuselectfunction", "char" => \$startMenuSelectFunction);
$templatesNode->register(">clitemplates>checkmenu", "char" => \$checkMenu);
$templatesNode->register(">clitemplates>endmenuselectfunction", "char" => \$endMenuSelectFunction);
$templatesNode->register(">clitemplates>startheaderfile", "char" => \$startHeaderFile);
$templatesNode->register(">clitemplates>headerdeclareparsetree", "char" => \$headerDeclareParseTree);
$templatesNode->register(">clitemplates>endheaderfile", "char" => \$endHeaderFile);
$templatesNode->register(">clitemplates>startaliaslist", "char" => \$startAliasList);
$templatesNode->register(">clitemplates>aliaslistentry", "char" => \$aliasListEntry);
$templatesNode->register(">clitemplates>endaliaslist", "char" => \$endAliasList);

#### Parse file and assign names to nodes
#
# Read CLI spec and parse
#

my $ret;

trace("Reading XML input...");

#
# Now read CLI spec files themselves
#

my %filesAlreadyParsed;
foreach $cliSpec (@ARGV)
{
    next if ( defined $filesAlreadyParsed{$cliSpec} );
    $filesAlreadyParsed{$cliSpec} = 1;

    trace(3, "Checking CLI spec file permissions");
    die "$progName: File ".$cliSpec." does not exist.\n" unless (-e $cliSpec);
    die "$progName: ".$cliSpec." is not a plain file\n" unless (-f $cliSpec);
    die "$progName: Can't read file ".$cliSpec."\n" unless (-r $cliSpec);

    trace(3, "Parsing CLI spec file '".$cliSpec."'");
    $ret = eval { $cliSpecNode->parsefile($cliSpec) };

    unless (defined $ret)
    {
        die "$progName: Error parsing CLI spec '".$cliSpec."' - error was: ".$@."\n";
    }
}

#
# Read templates file (either specified or default) and parse
#

unless (defined $templatesFile)
{
    trace(2, "No templates file supplied - defaulting to ".$defaultTemplatesFile);
    $templatesFile = $defaultTemplatesFile;
}

trace(3, "Checking templates file permissions");
die "$progName: File ".$templatesFile." does not exist.\n" unless (-e $templatesFile);
die "$progName: ".$templatesFile." is not a plain file\n" unless (-f $templatesFile);
die "$progName: Can't read file ".$templatesFile."\n" unless (-r $templatesFile);

trace(3, "Parsing templates file");
$cliSpec = $templatesFile;
$ret = eval { $templatesNode->parsefile($templatesFile) };

unless (defined $ret)
{
    die "$progName: Error parsing templates file - error was: ".$@."\n";
}

trace(3, "Checking for warnings in XML parsing");
if ($warnings > 0)
{
    die "$progName: Input files had ".$warnings." warnings (listed above) - aborting operation.\n";
}

trace(6, "Got \"startfile\" template") if $startFile;
trace(6, "Got \"startactionfunction\" template") if $startActionFunction;
trace(6, "Got \"startactionfunctioncheckargs\" template") if $startActionFunctionCheckArgs;
trace(6, "Got \"startactionfunctioncodeonly\" template") if $startActionFunctionCodeOnly;
trace(6, "Got \"startactionfunctioncheckargscodeonly\" template") if $startActionFunctionCheckArgsCodeOnly;
trace(6, "Got \"setfixedparam\" template") if $setFixedParam;
trace(6, "Got \"setvariableparam\" template") if $setVariableParam;
trace(6, "Got \"startactioncall\" template") if $startActionCall;
trace(6, "Got \"endfixedparams\" template") if $endFixedParams;
trace(6, "Got \"endactioncall\" template") if $endActionCall;
trace(6, "Got \"endfirstactioncall\" template") if $endFirstActionCall;
trace(6, "Got \"endactioncallsingle\" template") if $endActionCallSingle;
trace(6, "Got \"endactionfunction\" template") if $endActionFunction;
trace(6, "Got \"endactionfunctioncodeonly\" template") if $endActionFunctionCodeOnly;
trace(6, "Got \"declareparsetree\" template") if $declareParseTree;
trace(6, "Got \"starttreedeclaration\" template") if $startTreeDeclaration;
trace(6, "Got \"endtreedeclaration\" template") if $endTreeDeclaration;
trace(6, "Got \"startgeneratefunction\" template") if $startGenerateFunction;
trace(6, "Got \"addnode\" template") if $addNode;
trace(6, "Got \"addrootnode\" template") if $addRootNode;
trace(6, "Got \"addchildofroot\" template") if $addChildOfRoot;
trace(6, "Got \"stepback\" template") if $stepBack;
trace(6, "Got \"endgeneratefunction\" template") if $endGenerateFunction;
trace(6, "Got \"startheaderfile\" template") if $startHeaderFile;
trace(6, "Got \"headerdeclareparsetree\" template") if $headerDeclareParseTree;
trace(6, "Got \"endheaderfile\" template") if $endHeaderFile;
trace(6, "Got \"startmenuselectfunction\" template") if $startMenuSelectFunction;
trace(6, "Got \"checkmenu\" template") if $checkMenu;
trace(6, "Got \"endmenuselectfunction\" template") if $endMenuSelectFunction;


#
# Now we scan through the node tree and assign a unique name to each
# node - this will be used as the name for the associated action function.
#

trace("Assigning names to nodes...");

my %occurrences = ();    # Keeps trace of occurrences of node names, so we can
                         # make sure they're unique.

my @parents;
my $node;
my $name = "";
my $newNode;
my $token;
my $ch;

my $key;
my $value;

while (($key, $value) = each %action_functions)
{
    $name = "";
    foreach $token (split /\s+/, $key)
    {
        $name .= "_" if $name;
        foreach $ch (split //, $token)
        {
            if (ord($ch)>64 and ord($ch)<133 or    # Upper case letters
                ord($ch)>140 and ord($ch)<173 or   # Lower case letters
                ord($ch)>60 and ord($ch)<71 or     # Digits
                ord($ch) == 137)                   # Underscore
            {
                # Letters, digits and underscores can just be used as normal
                $name .= $ch;
            }
            # If neither of the conditions hold it's an illegal character
            # in an identifier, so omit it
        }
    }
    if (exists $occurrences{$name})
    {
        # We've got a clash, so append a character to make it unique
        $name .= $occurrences{$name}++;
    } else
    {
        $occurrences{$name} = 'A';
    }

    $value->{"name"} = $name;
}

trace(3, "Checking for warnings in summary string assignment");
if ($warnings > 0)
{
    die "$progName: Processing data caused ".$warnings." warnings (listed above) - aborting operation.\n";
}

if ($verbose > 3)
{
    my $key;
    my $value;
    ## Because we're require/importing Data::Dumper, in case the user doesn't
    ## have it installed, Perl doesn't notice the library uses these vars and
    ## complains we're only using them once. Hence I assign to them twice,
    ## for no other reason!
    $Data::Dumper::Terse = 0;
    $Data::Dumper::Indent = 0;
    $Data::Dumper::Terse = 1;
    $Data::Dumper::Indent = 1;
    trace(4, "Dumping parsed data:\n");
    print "---< KEYWORDS DUMP >---\n";
    print Dumper(\%keywords);
    print "---< USERS DUMP >---\n";
    while (($key, $value) = each %tree_roots)
    {
        print "\n".$key."\n";
        $value->display();
    }
    print "---< ACTION FUNCTIONS >---\n";
    print Dumper(\%action_functions);
    trace(4, "END OF DUMP");
}

#### Check consistency of input data
#
# We scan every tree and check that:
#  (a) Non-constant arguments are the sole child of their parent
#  (b) Constant arguments are NOT the sole child of their parent
#

trace("Verifying consistency of grammar...");

my @list;
my $flag;
@parents = ();

while (($key, $value) = each %tree_roots)
{
    $name = $key.":";
    $node = $value;
    while (defined $node)
    {
        $newNode = $node->eachChild();
        if (defined $newNode)
        {
            $name .= " ".$newNode->token_();
            # Reset the iterator
            $newNode->eachChild(0);
            $flag = 0;
            foreach $token (keys %keywords)
            {
                if ($token eq $newNode->token_())
                {
                    $flag = 1;
                    last;
                }
            }
            @list = $node->listChildren();
            if (exists $aliases{$newNode->token_()})
            {
                foreach my $child (@list)
                {
                    if ($child->token_() eq $aliases{$newNode->token_()})
                    {
                        print "Removing the \"".$aliases{$newNode->token_()}."\" command which clashes with alias for node \"$name\"\n";
                        my @children = ();
                        my $nextChild = 0;
                        while(defined $nextChild)
                        {
                            $nextChild = $node->popChild();
                            last if ($nextChild == $child);
                            push @children, $nextChild;
                        }
                        while ($nextChild = pop @children)
                        {
                            $node->pushChild($nextChild);
                        }
                        last;
                    }
                }
            }
            if (@list > 1)
            {
                if ($flag)
                {
                    warn "Node \"".$name."\" is a non-token argument, but has siblings\n";
                }
            } else
            {
                unless ($flag)
                {
                    warn "Node \"".$name."\" is a fixed argument but is the only child of its parent\n" unless defined $aliases{$newNode->token_()};
                }
            }
            if ($newNode->token_() =~ /^_|_$/)
            {
                unless ($flag)
                {
                    warn "Fixed argument \"".$name."\" contains leading or trailing underscores\n";
                }
            }
            push @parents, $node;
            $node = $newNode;
        } else
        {
            $node = pop @parents;
            $name =~ s/^(.*)\s+[^\s]+$/$1/;
        }
    }
}

trace(3, "Checking for inconsistencies in grammar");
if ($warnings > 0)
{
    die "$progName: Verifying grammar caused ".$warnings." warnings (listed above) - aborting operation.\n";
}

# Only continue if we're going to write the output

unless ($writeOutputFile)
{
    print "Skipping file output.\n\n";
    exit;
}

#### Finally we write the output file
#
# Generate some strings which can be eval'd to return interpolated template
# strings - this means converting:
#
#  "foo/bar ${baz}" --> "return qq/foo\/bar ${baz}/;"
#

trace("Generating output file...");

trace(3, "Converting template strings to suitable eval form");

$startFile = evalConvert($startFile);
$startActionFunction = evalConvert($startActionFunction);
$startActionFunctionCheckArgs = evalConvert($startActionFunctionCheckArgs);
$startActionFunctionCodeOnly = evalConvert($startActionFunctionCodeOnly);
$startActionFunctionCheckArgsCodeOnly = evalConvert($startActionFunctionCheckArgsCodeOnly);
$setFixedParam = evalConvert($setFixedParam);
$setVariableParam = evalConvert($setVariableParam);
$startActionCall = evalConvert($startActionCall);
$endFixedParams = evalConvert($endFixedParams);
$endActionCall = evalConvert($endActionCall);
$endFirstActionCall = evalConvert($endFirstActionCall);
$endActionCallSingle = evalConvert($endActionCallSingle);
$endActionFunction = evalConvert($endActionFunction);
$endActionFunctionCodeOnly = evalConvert($endActionFunctionCodeOnly);
$startGenerateFunction = evalConvert($startGenerateFunction);
$addRootNode = evalConvert($addRootNode);
$addChildOfRoot = evalConvert($addChildOfRoot);
$addNode = evalConvert($addNode);
$stepBack = evalConvert($stepBack);
$declareParseTree = evalConvert($declareParseTree);
$startTreeDeclaration = evalConvert($startTreeDeclaration);
$endTreeDeclaration = evalConvert($endTreeDeclaration);
$endGenerateFunction = evalConvert($endGenerateFunction);
$startMenuSelectFunction = evalConvert($startMenuSelectFunction);
$checkMenu = evalConvert($checkMenu);
$endMenuSelectFunction = evalConvert($endMenuSelectFunction);
$startHeaderFile = evalConvert($startHeaderFile);
$extraHeaders = evalConvert($extraHeaders);
$headerDeclareParseTree = evalConvert($headerDeclareParseTree);
$endHeaderFile = evalConvert($endHeaderFile);
$startAliasList = evalConvert($startAliasList);
$aliasListEntry = evalConvert($aliasListEntry);
$endAliasList = evalConvert($endAliasList);

#
# Open output file
#

trace(3, "Opening output file");
open OUTPUT, ">".$outputFile.".cc" or die "$progName: Failed to open file \"".$outputFile.".cc\" for output\n";

#
# All the variables we'll need to interpolate in the various templates
#

my $function_name = "";
my $param_type = "";
my $param_number = "";
my $action_name = "";
my $summary = "";

#
# Print header
#

my $indent = 0;

trace(3, "Printing header to output file");
my $string = eval $startFile;
indentCode($string, $indent);
print OUTPUT "\n".$string."\n";

# output any extra header files from the <extraheaders> sections
$string = eval $extraHeaders;
indentCode($string, $indent);
print OUTPUT "\n".$string."\n";

#
# Write out menu declaration for each user
#

trace(3, "Generating menu declarations");
while (defined($user = each %usernames))
{
    trace(6, "Menu declaration for user \"".$user."\"");
    $string = eval $declareParseTree;
    indentCode($string, $indent);
    print OUTPUT $string;
}
print OUTPUT "\n";

#
# Generate action functions
#

trace(3, "Generating action functions");

my $action;

while (($key, $value) = each %action_functions)
{
    # First count how many action calls there are for this action function
    # (as opposed to simple code blocks)
    my $num_actions = 0;
    foreach $action (@{$value->{"actions"}})
    {
        $num_actions++ if defined $action->{"action"};
    }
    $function_name = $value->{"name"};
    trace(5, "Generating action function \"".$function_name."\"");
    if ($value->{"extraargs"})
    {
        if ($num_actions > 0)
        {
            $string = eval $startActionFunction;
        }
        else
        {
            $string = eval $startActionFunctionCodeOnly;
        }
    } else
    {
        if ($num_actions > 0)
        {
            $string = eval $startActionFunctionCheckArgs;
        }
        else
        {
            $string = eval $startActionFunctionCheckArgsCodeOnly;
        }
    }
    indentCode($string, $indent);
    print OUTPUT $string;

    trace(5, "Generating action calls");
    $num = 0;
    $flag = 0;
    if ($num_actions == 1)
    {
        $flag = 1;
    }
    foreach $action (@{$value->{"actions"}})
    {
        $action_name = $action->{"action"};
        if (defined $action_name)
        {
            if (keys %{$action->{"params"}})
            {
                trace(6, "Starting call to action \"".$action_name."\"");
                $string = eval $startActionCall;
                indentCode($string, $indent);
                print OUTPUT $string;
            }

            while (($param_name, $param_value) = each %{$action->{"params"}})
            {
                trace(6, "Setting parameter \"".$param_name."\" to \"".$param_value."\"");
                my $param;
                foreach $param (keys %keywords)
                {
                    if ($param eq $param_value)
                    {
                        $param_number = 0;
                        foreach $token (split /\s+/, $key)
                        {
                            if ($token eq $param)
                            {
                                $param_value = $param_number;
                                last;
                            }
                            $param_number++;
                        }
                        last;
                    }
                }
                if (not $param_value =~ /^[0-9]+$/)
                {
                    $param_value = "\"".$param_value."\"";
                    $param_name = "\"".$param_name."\"";
                    $string = eval $setFixedParam;
                    indentCode($string, $indent);
                    print OUTPUT $string;
                } else
                {
                    $param_name = "\"".$param_name."\"";
                    $string = eval $setVariableParam;
                    indentCode($string, $indent);
                    print OUTPUT $string;
                }
            }
            if (keys %{$action->{"params"}})
            {
                trace(6, "Ending fixed parameters");
                $string = eval $endFixedParams;
                indentCode($string, $indent);
                print OUTPUT $string;
            }

            if ($flag)
            {
                trace(6, "Ending call to action \"".$action_name."\"");
                $string = eval $endActionCallSingle;
                indentCode($string, $indent);
                print OUTPUT $string;
            } else
            {
                if ($num == 0)
                {
                    trace(6, "Ending call to action \"".$action_name."\"");
                    $string = eval $endFirstActionCall;
                    indentCode($string, $indent);
                    print OUTPUT $string;
                } else
                {
                    trace(6, "Ending call to action \"".$action_name."\"");
                    $string = eval $endActionCall;
                    indentCode($string, $indent);
                    print OUTPUT $string;
                }
            }
            $num++;
        }
        else
        {
            # This is a simple code block, so just paste it into the output
            my $code = $action->{"code"};
            if (defined $code)
            {
                indentCode($code, $indent);
                print OUTPUT $code;
                print OUTPUT "\n";
            }
        }
    }
    if ($num_actions == 0)
    {
        trace(5, "Ending code-only action function");
        $string = eval $endActionFunctionCodeOnly;
        indentCode($string, $indent);
        print OUTPUT $string;
    }
    elsif (not $flag)
    {
        trace(5, "Ending action function");
        $string = eval $endActionFunction;
        indentCode($string, $indent);
        print OUTPUT $string;
    }
    print OUTPUT "\n";
}

#
# Build each user's parse tree in turn
#

my $word;

trace(3, "Building tree-creation function");
while (($key, $value) = each %tree_roots)
{
    $num = 0;
    $user = $key;
    $string = eval $startTreeDeclaration;
    indentCode($string, $indent);
    print OUTPUT $string;
    print OUTPUT "\n";

    $name = $key.":";
    $node = $value;
    $flag = 1;
    while (defined $node)
    {
        $newNode = $node->eachChild();
        if (defined $newNode)
        {
            if ($num > 0)
            {
                $string = eval $stepBack;
                indentCode($string, $indent);
                print OUTPUT $string;
                $num = 0;
            }
            $name .= " ".$newNode->token_();
            trace(6, "Adding node \"".$name."\"");
            # Reset the iterator
            $newNode->eachChild(0);

            if (defined $newNode->action_())
            {
                $function_name = $action_functions{$newNode->action_()}->{"name"};
            } else
            {
                $function_name = "NULL";
            }
            $token = $newNode->token_();
            foreach $word (keys %keywords)
            {
                if ($token eq $word)
                {
                    $token =~ s/^_*(.*[^_])_*$/$1/;
                    $token = "<".$token.">";
                    last;
                }
            }
            $summary = $newNode->summary_();
            $summary = "" unless defined $summary;
            $summary = "\"".$summary."\"";
            $token = "\"".$token."\"";
            if ($flag)
            {
                $string = eval $addChildOfRoot;
                $flag = 0;
            } else
            {
                $string = eval $addNode;
            }
            indentCode($string, $indent);
            print OUTPUT $string;

            push @parents, $node;
            $node = $newNode;
        } else
        {
            $node = pop @parents;
            $name =~ s/^(.*)\s+[^\s]+$/$1/;
            if (defined $node)
            {
                $num++;
            }
        }
    }
    $string = eval $endTreeDeclaration;
    indentCode($string, $indent);
    print OUTPUT $string;
}

#
# Write out start of generate function
#

trace(3, "Generating tree-creation function");
$string = eval $startGenerateFunction;
indentCode($string, $indent);
print OUTPUT $string;

$string = eval $startAliasList;
indentCode($string, $indent);
print OUTPUT $string;

my $aliasFrom;
my $aliasTo;
while (($aliasFrom, $aliasTo) = each %aliases)
{
    $string = eval $aliasListEntry;
    indentCode($string, $indent);
    print OUTPUT $string;
    $num++;
}

$string = eval $endAliasList;
indentCode($string, $indent);
print OUTPUT $string;

#
# Create the top-level root nodes
#

trace(3, "Generating root nodes");
while (defined($user = each %tree_roots))
{
    trace(6, "Root node for user \"".$user."\"");
    $string = eval $addRootNode;
    indentCode($string, $indent);
    print OUTPUT $string;
}
print OUTPUT "\n";

#
# Write out end of generate function
#

trace(3, "Ending tree-creation function");
$string = eval $endGenerateFunction;
indentCode($string, $indent);
print OUTPUT $string;

#
# Write out menu selection function
#

trace (3, "Starting menu selection function");
$string = eval $startMenuSelectFunction;
indentCode($string, $indent);
print OUTPUT $string;

while (defined ($user = each %usernames))
{
    trace (6, "Adding menu check for user \"".$user."\"");
    my $level = $userlevels{$user};
    $string = eval $checkMenu;
    indentCode($string, $indent);
    print OUTPUT $string;
}

trace (3, "Starting menu selection function");
$string = eval $endMenuSelectFunction;
indentCode($string, $indent);
print OUTPUT $string;

#
# Close output file
#

close OUTPUT;

#
# Open output header file
#

trace(3, "Opening output header file");
open OUTPUT, ">".$outputFile.".h" or die "$progName: Failed to open file \"".$outputFile.".h\" for output\n";

#
# Print header
#

$indent = 0;

trace(3, "Printing header to output header file");
$string = eval $startHeaderFile;
indentCode($string, $indent);
print OUTPUT "\n".$string."\n";

#
# Create the top-level root nodes
#

trace(3, "Generating root node declarations for header file");
while (defined($user = each %tree_roots))
{
    trace(6, "Root node for user \"".$user."\"");
    $string = eval $headerDeclareParseTree;
    indentCode($string, $indent);
    print OUTPUT $string;
}
print OUTPUT "\n";

#
# Write out end of header file
#

trace(3, "Ending header file");
$string = eval $endHeaderFile;
indentCode($string, $indent);
print OUTPUT $string;

close OUTPUT;

exit;


#### Callback functions for parsing the CLI spec
#
# handleVersion() is called after the "scriptversion" tag is finished - the
# variable $required_version contains the contents of the tag. If this
# script is not at least that version, we die.
#

sub handleVersion
{
    if ($required_version > $version)
    {
        warn "File ".$cliSpec." requires version ".$required_version." of parser - this script is version ".$version."\n";
    }
    if ($cliSpec =~ /templates\.xml/ and
        $required_templates_version > $required_version)
    {
        warn "File ".$cliSpec." only requires version ".$required_version.", whereas this script is only compatible with versions of the file which require version ".$required_templates_version." or later\n";
    }
    $required_version = "";
}

sub handleAlias
{
    if (defined $aliases{$alias_from} and $aliases{$alias_from} ne $alias_to)
    {
        warn "Token '$alias_from' is aliased to '$alias_from' in file $cliSpec when it is already aliases to '$aliases{$alias_from}' elsewhere\n";
    } else
    {
        $aliases{$alias_from} = $alias_to;
    }
    $alias_from = "";
    $alias_to = "";
}

#
# handleExtraHeaders() - adds contents onto the end of $startHeaderFile

sub handleExtraHeaders
{
    $extraHeaders .= "/* Extra includes from ".$cliSpec." */";
    $extraHeaders .= "\n";
    $extraHeaders .= $extra_headers;
    $extra_headers = "";
}

#
# handleKeyword() is called at the end of the "keyword" tag - attributes "id"
# and "type" are available as $keyword_id and $keyword_type. They are added
# to %keywords.
#

sub handleKeyword
{
    my $context = shift;

    trace(5, "End of <keyword> at line ".$context->current_line());
    trace(6, "id => \"".$keyword_id."\"");
    trace(6, "type => \"".$keyword_type."\"");

    unless (checkAttr("keyword", $keyword_id => "id", $keyword_type => "type"))
    {
        if (exists $keywords{$keyword_id})
        {
            if ($keywords{$keyword_id} ne $keyword_type)
            {
                warn "Second instance of keyword \"".$keyword_id."\" before line ".$context->current_line()." of file ".$cliSpec."has different type (\"".$keyword_type."\") to first definition\n";
            }
        } else
        {
            $keywords{$keyword_id} = $keyword_type;
        }
    }
    $keyword_id = "";
    $keyword_type = "";
}

#
# handleUser() is called at the end of the "user" tag - the contents of the
# tag are available in variable $user. It is added to @users.
#

sub handleUser
{
    my $context = shift;

    my $var;
    my $flag = 0;

    trace(5, "End of <user> at line ".$context->current_line());
    trace(6, "user => \"".$user."\"");

    unless (checkAttr("user", $user => "_contents_"))
    {
        unless (defined $usernames{$user})
        {
            warn "User \"".$user."\" not defined in atmos/source/im/shared/User.cc\n";
        }
        foreach $var (@users)
        {
            if ($var eq $user)
            {
                warn "User \"".$user."\" specified twice before line ".$context->current_line()." of file ".$cliSpec."\n";
                $flag = 1;
            }
        }
        unless ($flag)
        {
            push @users, $user;
            my $level = $usernames{$user};
            foreach $var (keys %usernames)
            {
                my $var2;
                if ($usernames{$var} > $level)
                {
                    $flag = 0;
                    foreach $var2 (@users)
                    {
                        if ($var2 eq $var)
                        {
                            $flag = 1;
                            last;
                        }
                    }
                    trace(4, "Implicitly adding user \"".$var."\" with higher access than user \"".$user."\" before line ".$context->current_line()." of file ".$cliSpec."\n");
                    push @users, $var unless $flag;
                }
            }
        }
    }
    $user = "";
}

#
# handleParam() is called at the end of a parameter declarations - the
# attributes "name" and "value" are available as $param_name and $param_value.
# They are added to %params.
#

sub handleParam
{
    my $context = shift;

    $param_name =~ s/\"/\\\"/g;
    $param_value =~ s/\"/\\\"/g;

    trace(5, "End of <param> at line ".$context->current_line());
    trace(6, "name => \"".$param_name."\"");
    trace(6, "value => \"".$param_value."\"");

    unless (checkAttr("param", $param_name => "name", $param_value => "value"))
    {
        if (exists $params{$param_name})
        {
            warn "Second instance of param \"".$param_name."\" near line ".$context->current_line()." of file ".$cliSpec."\n";
        } else
        {
            $params{$param_name} = $param_value;
        }
    }
    $param_name = "";
    $param_value = "";
}

#
# handleAction() is called at the end of an action declaration. It has
# an attribute "id" available as $action_id, and also uses @params. It adds
# the action to @actions.
#

sub handleAction
{
    my $context = shift;

    $action_id =~ s/\"/\\\"/g;

    trace(5, "End of <action> at line ".$context->current_line());
    trace(6, "id => \"".$action_id."\"");

    unless (checkAttr("action", $action_id => "id"))
    {
        my $key;
        my $value;
        my $hashref = { "action" => $action_id };
        while (($key, $value) = each %params)
        {
            $hashref->{"params"}->{$key} = $value;
        }
        push @actions, $hashref;
    }
    $action_id = "";
    %params = ();
}

#
# handleCommand() is called at the end of a command tag. It has the
# contents of the "syntax" tag available as $command_syntax and also uses
# @users and @actions.
#

sub handleCommand
{
    my $context = shift;

    my $user;
    my $root;
    my $ref;
    my $var;

    $command_syntax =~ s/\"/\\\"/g;

    trace(5, "End of <command> at line ".$context->current_line());
    trace(6, "syntax => \"".$command_syntax."\"");

    unless (checkAttr("syntax", $command_syntax => "_contents_"))
    {
        unless (@users)
        {
            warn "Command \"$command_syntax\" has no users specified\n";
        }

        # We need to add this command to the trees for every user who can
        # execute it
        foreach $user (@users)
        {
            my $flag;
            while (defined($var = each %tree_roots))
            {
                if ($var eq $user)
                {
                    $flag = 1;
                    last;
                }
            }
            # Reset iterator
            keys %tree_roots;
            $tree_roots{$user} = TreeNode->new() unless $flag;

            # Scan through node tree so far to reach appropriate leaf nodes.
            # If we have tokens for which there is no child, we create the
            # appropriate nodes as we descend the tree.
            $root = $tree_roots{$user};
            my $currentNode = $root;
            my $token;
            my $node;
            my $foundNode;
            foreach $token (split /\s+/, $command_syntax)
            {
                # Scan through children of current node for a node of the
                # same name as the current token
                $foundNode = undef;
                foreach $node ($currentNode->listChildren())
                {
                    if (($node->token_()) eq $token)
                    {
                        $foundNode = $node;
                        last;
                    }
                }
                $node = $foundNode;
                $flag = 0;
                unless (defined $node)
                {
                    $flag = 1;
                    $node = TreeNode->new();
                    $node->token_($token);
                    $currentNode->pushChild($node);
                }
                $currentNode = $node;
            }

            $currentNode->action_($command_syntax);
        }

        # Now store the list of actions
        $ref = [];
        if (defined $action_functions{$command_syntax}->{"actions"})
        {
            $ref = $action_functions{$command_syntax}->{"actions"};
        }
        foreach $var (@actions)
        {
            push @$ref, $var;
        }
        $action_functions{$command_syntax}->{"actions"} = ($ref);
        if (defined $extra_args && uc($extra_args) eq "TRUE")
        {
            $action_functions{$command_syntax}->{"extraargs"} = 1;
        } else
        {
            $action_functions{$command_syntax}->{"extraargs"} = 0;
        }
    }
    $command_syntax = "";
    @users = ();
    @actions = ();
}

#
# handleCode - called at the end of a <code> tag.
#
sub handleCode
{
    my $context = shift;

    trace(5, "End of <code> at line ".$context->current_line());

    my $key;
    my $value;
    my $hashref = { "code" => $commandCode };
    push @actions, $hashref;

    $commandCode = "";
}


#
# handleNode() is called at the end of a "node" tag. It has the "name"
# attribute of the node tag and the contents of the "summar" tag available
# to it as $node_id and $node_summary respectively. It adds them to %nodes.
#

sub handleNode
{
    my $context = shift;

    $node_id =~ s/\"/\\\"/g;
    $node_summary =~ s/\"/\\\"/g;

    trace(5, "End of <node> at line ".$context->current_line());
    trace(6, "id => \"".$node_id."\"");

    unless (checkAttr("node", $node_id => "id"))
    {
        if (exists $nodes{$node_id})
        {
            warn "second instance of node \"".$node_id."\" before line $.".$context->current_line()." of file ".$cliSpec."\n";
        } else
        {
            my $flag = 0;
            my $user;
            my $root;
            my $node;
            while (($user, $root) = each %tree_roots)
            {
                $node = $root->findNode("token", $node_id);
                if (defined $node)
                {
                    trace(6, "Setting summary for user \"".$user."\"");
                    $flag = 1;
                    $node->summary_($node_summary);
                }
            }
            warn "no node in any tree matches \"".$node_id."\"\n" unless $flag;
            $nodes{$node_id} = $node_summary;
        }
    }
    $node_id = "";
    $node_summary = "";
}

#### Other utility functions
#
# checkAttr() is a simple function which takes the name of a tag, and then
# a list of pairs of (parameter value, parameter name) - if any of the former
# are empty it prints the appropriate warnings. It returns the number
# of variables that were empty.
#

sub checkAttr
{
    my $context = shift;
    my $tag = shift;
    my $var;
    my $name;
    my $flag = 0;

    while (($var, $name) = splice @_, 0, 2)
    {
        die "$progName: Undefined value checked as attribute \"".$name."\" of tag \"".$tag."\"" unless defined $var;
        unless ($var)
        {
            if ($name eq "_contents_")
            {
                warn $tag." tag is empty (or no tag) before line ".$context->current_line()."of file ".$cliSpec."\n";
            } else
            {
                warn $tag." tag before line ".$context->current_line()." of file ".$cliSpec."has no \"".$name."\" attribute (or attribute is empty)\n";
            }
            $flag++;
        }
    }

    return $flag;
}

#
# trace() is a simple function for printing output at higher levels of
# verbosity. If a single argument is supplied, it prints it at level 1
# (default level of verbosity - displayed unless --quiet used), otherwise
# the first argument is the level of verbosity at which the message should
# be displayed. Note that a message traced at level 0 will be displayed even
# if --quiet is used
#

sub trace
{
    my $arg1 = shift;
    my $arg2 = shift;
    if (defined $arg2)
    {
        print "[".$arg1."] "."-"x($arg1 - 1)." ".$arg2."\n" if ($verbose >= $arg1);
    } elsif (defined $arg1)
    {
        print "\n" if ($verbose > 1);
        print $arg1."\n\n" unless ($verbose == 0);
    } else
    {
        die "$progName: Empty call to trace()";
    }
}

#
# evalConvert() turns a normal string into one that can be eval'd to return
# the original string but with any variables interpolated.
#

sub evalConvert
{
    my $string = shift;

    #
    # We strip all leading and trailing whitespace from each line, unless the
    # user has specified an indent step of zero (i.e. don't re-indent)
    #

    if ($indentStep)
    {
        # First strip all leading/trailing whitespace, including blank lines
        $string =~ s/^\s*(.*[^\s])\s*$/$1/s;
        # Then string all leading/trailing whitespace on each line
        $string =~ s/^[ \t]*(.*[^\s])[ \t]*$/$1/mg;
    }

    #
    # Now escape all dodgey characters and convert to an eval()able form.
    #

    $string =~ s!\\!\\\\!sg;
    $string =~ s!/!\\/!sg;
    $string = 'return qq/'.$string.'\n/;';

    return $string;
}

#
# indentCode() takes a chunk of code and existing indentation as arguments
# and modifies them in-place. It indents the code as appropriate and adjusts
# the current indentation level. It currently uses very simple indentation
# rules which are probably sufficient for the simple code this program
# generates, but which don't produce amazing results. It uses the global
# variable $indentStep - if it's zero, no indentation is performed.
#

sub indentCode
{
    my $line;
    my $output = "";

    if ($indentStep)
    {
        foreach $line (split /\n/, $_[0])
        {
            if ($line =~ /\}/)
            {
                $_[1] -= $indentStep;
            }
            $output .= (" "x$_[1]).$line."\n";
            if ($line =~ /\{/)
            {
                $_[1] += $indentStep;
            }
#           if ($line =~ /\(/)
#           {
#               $_[1] += $indentStep;
#           }
#           if ($line =~ /\)/)
#           {
#               $_[1] -= $indentStep;
#           }
        }
        $_[0] = $output;
    }
}


__END__


=head1 NAME

cli_parser - XML CLI spec to C code translator

=head1 SYNOPSIS

B<cli_parser> [ options ] F<clispec.xml> ...

=head1 DESCRIPTION

cli_parser is a utility used to convert a CLI specification, written in
XML, into a block of C code. This code contains a set of action functions
which are used by the CLI process under ISOS to implement the effects of
console commands.

=head1 OPTIONS

Command-line options listed here can all be shortenened to the shortest
unique prefix (the program will halt if there are multiple expansions).

=over 4

=item --output F<file>

Specifies the file to which output should be directed. Use the --help option
to display the default filename used if this option is not specified.

=item --templates F<file>

Specifies the XML file to use for the C++ templates. These templates are used
to generate the C++ output file. Defaults to:
F<source/webserver/atmos/cli/templates.xml>


=item --nowriteoutput

Causes the program to halt just prior to writing the output file - this is
typically useful for checking the syntax of a CLI specification file before
using it.

=item --verbose [ <level> ]

Increases the amount of debugging output the program generates. Optionally
an integer can be specified as an argument to this option - this sets the
level of verbosity. If --verbose is specified without an argument, the
level of verbosity is set to 2. If --verbose is not specified, the level
defaults to 1. Messages that are only displayed at levels greater than 1 are
prefixed with the level at which they are displayed. The available levels are:

=over 4

=item 0

Only outputs fatal errors

=item 1

Displays brief progress information

=item 2

Displays when values are falling back to their defaults

=item 3

Displays more detailed progress information

=item 4

Displays a dump of the parsed data from the XML files

=item 5

Displays yet more detailed progress messages during parsing

=item 6

Displays values of values read in during parsing

=item 7

Displays a complete dump of the internal node tree after parsing, including
all internal fields

=back

=item --quiet

Equivalent to --verbose 0. This option overrides --verbose.

=item --version

Displays the current version number then exits.

=item --help

Displays a summary of command-line help.

=back

=head1 EXAMPLES

C<B<bash$> cli_parser ip_cli.xml bridge_cli.xml ppp_cli.xml>

=head1 FILES

F<source/webserver/atmos/cli/templates.xml>

F<source/E<lt>moduleE<gt>/mapi/E<lt>moduleE<gt>.xml>

=head1 SEE ALSO

Nothing, as yet.

=head1 BUGS

Blank lines in templates are not handled correctly.

Indentation only performed for code within braces.

It isn't possible to specify the locations of User.cc and User.h from
the command-line.

=head1 AUTHOR

A. Pearce

=cut

