\lchapter{Kepago}

Kepago is a simple imperative programming language in the style of C or Pascal.
It was designed as a substitute for the unknown language used by \vas{}
themselves.  The reference implementation remains my \file{kpc} compiler for
AVG32.

The present implementation of Kepago for \reallive\ is limited in scope; it
currently lacks major features such as user-defined functions, which limits its
expressivity considerably.  It is, however, adequately usable for simple
programming tasks.

\lsection{Lexical structure}

  The encoding of a file is determined by the default encoding for which
  \compiler{} was compiled (this is CP932 in the standard configuration), and
  can be overridden on a case-by-case basis on the command line.

  Identifiers can use almost any character defined in the current encoding.
  They are not case-sensitive.  They may not begin with numbers, or with the
  reserved characters \$ and @.  Identifiers beginning and/or ending with two
  underscores are reserved for internal use: they are valid, but you should
  avoid using them except for the specific cases documented in this manual.

  Numbers are decimal by default; digits can be separated with underscores, as
  in ML\@.  Hexadecimal numbers are identified by a prefix \$, as in Pascal.
  Binary numbers take the prefix \$\#, and octal numbers \$\%.

  Comments come in two flavours.  Line comments begin with \verb|//|, and
  block comments (which behave like C comments, i.e.\ they cannot be nested)
  are delimited by \verb|{-| and \verb|-}|.

\lsection{Structure of a file}

  A Kepago file is simply a text file containing a sequence of statements and
  definitions.  There is no statement separator: statements are neither
  line-delimited like Basic nor semicolon-delimited like C and Pascal, although
  line breaks and commas can be used almost arbitrarily to separate them for
  clarity.

  \index{eof}
  A file can be ended with the \lstinline|eof| keyword; nothing following this
  will be processed by \compiler.

\index[concept]{expressions}
\lsection{Expressions}

  Expressions are fairly ordinary.  The following binary operators are
  recognised.  Their meanings are identical to C, but their precedence is not:
  \begin{lstlisting}[escapechar=@]
    << >>
    *  /  %  &   // higher precedence
    +  -  |  ^
    >= >  <= <
    == !=
    &&           // lower precedence
    ||
  \end{lstlisting}
  \noindent In addition, the operators \lstinline|-~!| are recognised as unary
  operators, again with the same semantics as in C; these all have equal
  precedence greater than any binary operation.  Precedence can, as usual, be
  overridden with parentheses.

  The arithmetic operators (from \lstinline{|} upwards) can have an
  \lstinline|=| appended to form assignment operators, again as in C; note
  however that these cannot be used on the right-hand side of an expression or
  within function calls.  There are currently no unary increment/decrement
  operators and no address or pointer dereference operators.

  Example:
  \begin{lstlisting}
    x = 1
    x += (strlen(s) + 2) * 3
  \end{lstlisting}

  When processing strings, the only permitted operator is \lstinline|+|, which
  performs string concatenation. It is also legal, within integer expressions,
  to compare strings with the comparison operators.  Apart from that it is not
  legal to mix strings and integers in expressions, though the various integer
  types may be mixed freely.

  \label{constexprs}\index[concept]{constants}\index[concept]{expressions!constant}
  A number of Kepago constructs utilise the concept of a ``constant
  expression''. This refers to any expression that can trivially be fully
  evaluated at compile-time.  A constant expression may contain the full range
  of operations, and it may refer to constant symbols, but not variables.  It
  may also contain calls to certain functions, such as \fnref{max}, that can
  be evaluated at compile-time, and to a set of macros, such as
  \fnref{defined?}, that are always evaluated at compile-time.

\lsection{Statements}

  In addition to the statement types detailed in this section, it is also valid
  to use a string expression by itself as a statement, which is how text display
  is normally accomplished.  This topic is discussed in depth in section
  \ref{sec:strings}.

  \lsubsection{Blocks and scopes}

    Anywhere a statement is valid, it can be replaced with a block.  Blocks are
    opened with \lstinline|:| and closed with \lstinline|;|, and function in much
    the same way as braces in C-style languages.

    Statement blocks double as scoping constructors.  Symbols are visible only
    within the scope in which they are defined, or scopes nested within it.  For
    example:
    \begin{lstlisting}
      int foo = 1
      if (foo == 1):
        int bar = 2
        'foo is \i{foo} and bar is \i{bar}' // prints "foo is 1 and bar is 2"
        pause;
      'foo is \i{foo}' // prints "foo is 1"
      'bar is \i{bar}' // compile-time error: bar is not visible in the outer scope
      pause
    \end{lstlisting}

  \fnidx{goto}\fnidx{gosub}
  \lsubsection{Labels}\label{sec:labels}

    While higher-level control structures should be used where possible, program
    flow may also be controlled with \fnrefnoparens{goto},
    \fnrefnoparens{gosub}, and related functions.  Labels for use with
    \lstinline|goto| statements can be defined at any point where a statement is
    valid; a label is any valid identifier beginning with \lstinline|@|. The
    scope of a label is global; if the same label is defined multiple times, a
    warning is issued and the later definition is used.

    Example:
    \begin{lstlisting}
      @loop
        'This text is displayed repeatedly in an infinite loop.'
        pause
        goto @loop
    \end{lstlisting}
    You should, of course, write this instead:
    \begin{lstlisting}
      while 1:
        'This text is displayed repeatedly in an infinite loop.'
        pause;
    \end{lstlisting}
    \compiler{} optimises conditional tests away when the conditions can be
    evaluated at compile-time, so it generates identical code in both cases.

  \lsubsection{Variable declarations}\index[concept]{variables}

    \lsubsubsection{Declaration syntax}

      Declaration statements are of the form

      \noindent\metavar{type}~[(\metavar{directives})]~\metavar{variables}

      \noindent\metavar{type} is the type given to all the variables declared
      by this statement, \metavar{directives} is an optional parenthesised list
      of flags that control their declaration, and \metavar{variables} is a
      comma-separated list of declarations.

      Each declaration in \metavar{variables} consists of an identifier which
      may optionally be followed by an array declaration (see next section), an
      initial value, and/or an address specifier.  Initial values are declared
      with the form \metavar{identifier}\lstinline| = |\metavar{value}; addresses
      are declared with the form
      \metavar{identifier}\lstinline| -> |\metavar{space}.\metavar{address}.  For
      example:
      \begin{lstlisting}
        byte a                    // value undefined, address automatic
        byte b = 2                // initialised to 2, address automatic
        byte c -> MEMARR_A.4000   // value undefined, address A8b[4000]
        byte d = 2 -> MEMARR_Z.10 // initialised to 2, address Z8b[10]
      \end{lstlisting}

      The types currently supported are:

      \begin{tabular}{l@{\hs}l}
      \texttt{int} & 32-bit integer \\
      \texttt{byte} & 8-bit integer \\
      \texttt{bit4} & 4-bit integer \\
      \texttt{bit2} & 2-bit integer \\
      \texttt{bit}  & 1-bit integer \\
      \texttt{str}  & character string
      \end{tabular}

      The directives currently supported are:

      \index{block}\prespace\texttt{block}
      \begin{cmdesc}
        Ensures that all variables declared in the one statement are allocated
        contiguously, and, in the case of integers smaller than 32 bits, ensures
        that they are packed.
        
        An example will illustrate the use of this:
        \begin{lstlisting}
          int x, y, z
          sum (x, z)          // value is undefined
          int(block) x, y, z  // x, y, and z guaranteed to be contiguous
          sum (x, z)          // guaranteed to equal x + y + z
        \end{lstlisting}
      \end{cmdesc}

      \index{zero}\prespace\texttt{zero}
      \begin{cmdesc}
        Ensure that the allocated memory is initialised.  Integers not otherwise
        given initial values will be set to 0; strings will be set to the empty
        string.
      \end{cmdesc}

      \index{labelled}\prespace\texttt{labelled}
      \begin{cmdesc}
        If the \cllong{flag-labels} option was passed to \compiler{}, entries
        will be created in \file{flag.ini} for variables declared with this
        directive.
      \end{cmdesc}

      \index{ext}\prespace\texttt{ext}
      \begin{cmdesc}
        Variables declared \texttt{ext} are not constrained by enclosing 
        blocks; they remain in scope permanently from the point of their 
        declaration unless deallocated manually.        
      \end{cmdesc}

    \lsubsubsection{Arrays}

      Arrays are allocated in the same way as other variable declarations, with
      the addition of an array declaration immediately following the variable's
      identifier.  This consists of the standard square brackets surrounding
      an integer constant giving the array's length.

      An array can be initialised in any of three ways.  Firstly, if the
      \texttt{zero} directive is included in the declaration, the memory
      allocated will be cleared automatically.  Secondly, if a single expression
      is given as an initial value, every member of the array will be initialised
      to that value.  Finally, individual members of the array can be initialised
      by providing a tuple as the initial value:
      \begin{lstlisting}
        int a[5] = { 1, 2, 3, 4, 5 }
      \end{lstlisting}
      \noindent In this last case, and only in this case, the square brackets
      may be left empty, and the length of the array will be set automatically to
      the number of elements provided:
      \begin{lstlisting}
        str strings[] = { 'foo', 'bar', 'baz' }
      \end{lstlisting}

      Only one-dimensional arrays are supported.

    \lsubsubsection{Caveats}

      Memory allocation is currently handled statically based on the settings
      passed to \fnref{rlcSetAllocation}.

      All blocks allocated are word-aligned: that is to say, 
      \lstinline|bit x, y, z| allocates three whole words even though only three 
      bits are being used.  You can get round this by allocating variables of 
      smaller sizes in arrays or with the \texttt{block} directive.

      Be aware that the variable allocation system is \emph{not sound}.
      \begin{lstlisting}
        if 1:
          int x = 0
          gosub @oops
          'x = \i{x}'
          pause
        ;              // end of scope, x implicitly deallocated
        end

        @oops
          int y = 1    // y allocated at the same address as x
          ret
      \end{lstlisting}
      \noindent prints \lstinline|x = 1|, not \lstinline|x = 0|, even though
      the value of the logical variable \lstinline|x| was never modified!
      Safe usage of the current system requires that any variables be allocated
      outside the largest scope in which they are used; in the example above,
      \lstinline|x| would have to be declared at the top level, and any variable
      which is to be used after a call to another scenario should be declared
      globally in a project header file to ensure that its memory will not be
      used for anything else unintentionally.

      A future version of \compiler{} will hopefully introduce dynamic memory
      allocation, which will mitigate these problems to some extent.

  \lsubsection{Constant declarations}

    ``Constant'' implies that the value is always known to the compiler, not
    that the value is immutable; Kepago constants are actually more like
    compile-time variables than constants in the strict sense.

    Constants can hold integer or string values, and can be used in expressions
    wherever a literal would be valid.

    They are handled with the following directives (see also \ref{sec:directives}).

    \dirdef{define}
    \lstinline|#define|~\metavar{IDENT}
    \begin{cmdesc}
      Defines the symbol \metavar{IDENT}.  Multiple symbols can be defined at
      once, separated by commas.  The value bound to \metavar{IDENT} is
      a non-zero integer.

      The scope of a symbol defined with this directive is not constrained by
      blocks; it remains defined in all code that is \emph{compiled} subsequent
      to its definition.  In the current state of the implementation, this
      effectively means that it remains defined to the end of the file.  Once
      user-defined functions are implemented things will become a little more
      complicated.
    \end{cmdesc}

    \dirdef{undef}
    \lstinline|#undef|~\metavar{IDENTS}
    \begin{cmdesc}
      Undefines the given symbol(s).

      At present, the only symbols which may be undefined manually are those
      which were defined globally with \dirref{define}.
    \end{cmdesc}

    \dirdef{const}
    \lstinline|#const|~\metavar{IDENT}~\lstinline{=}~\metavar{EXPR}
    \begin{cmdesc}
      Defines a new constant symbol.  The constant expression \metavar{EXPR}
      (see \ref{constexprs}) is evaluated, and its value assigned to
      \metavar{IDENT}.

      Multiple symbols can be defined at once, separated by commas.

      The scope of a symbol defined with this directive is limited to the current
      block.
    \end{cmdesc}

    \dirdef{set}
    \lstinline|#set|~\metavar{IDENT}~\lstinline|=|~\metavar{EXPR}
    \begin{cmdesc}
      Mutates the value assigned to the symbol \metavar{IDENT}.  This does not
      affect the symbol's scope.

      As a shortcut, you can use the form \lstinline|#set foo += 1| instead of
      \lstinline|#set foo = foo + 1|; the same goes for other arithmetic operators.
    \end{cmdesc}

  \lsubsection{Inlines/Macros}\label{sec:inlines}
  
    {In C, \lstinline|#define| statements can be used to specify function like 
	macros which can accept multiple parameters and which are replaced with a 
	macro's result when expanded by the C preprocessor.
	
	Similar syntactic magic can be conjured up within a kepago file by making use
	of an inline macro definition.  Note however that while it's convenient to
	imagine that C and kepago macros are equivalent, the syntax used to define
	such macros diverge, so it might be useful to dismiss such convenient fantasies
	and read on.}
	
    \dirdef{inline}
	\lstinline|#inline|~\metavar{IDENT}(<arg1>,<arg2>~\lstinline|=|~\metavar{EXPR}[<arg2>]~{\ldots~})~\lstinline|:|~\metavar{STMTS}~\lstinline|;|
    \begin{cmdesc}
      Defines a macro which can be used (as a macro call) within expressions.  
	  The macro call is expanded during compilation and replaced inline with the
	  resulting constant expression.  As the macro call vanishes entirely during
	  the compilation phase it would be a mistake to confuse an inline macro call
	  with an actual function call which generates bytecode that performs an actual
	  call which returns a value upon completion.  So don't be a fool!
	  
      It might also be considered lazy thinking to conflate so-called intrinsic
	  functions with inline macros.  While both perform feats of shapeshifting
	  when encountered by the rlc compiler, intrinsic functions are predefined
	  within the compiler itself rather than being defined in terms of kepago
	  statements as inline macros are.
	  
	  User-defined functions remain a potential feature to possibly be implemented 
	  in some alternate future version whose existence is only found in the shady
	  realm of urban legends between fits of delerium tremens.

	  If this has failed to clarify the situation and confusion prevails, a
	  round of hands on coding experience and experimentation may lie in your
	  immediate future.  May the wistful spirit of kepago be with you as you
	  go forward into the unknown.
	  
	  There are plenty of inline macros to explore in library files bearing the
	  .kh extension.  This might be a wise place to fortify your kepago skills.
    \end{cmdesc}

  \lsubsection{Directives}\label{sec:directives}

    Like in C, directives (that is, statements which modify compiler state
    rather than generating code) begin with a hash sign \lstinline|#|; unlike in
    C, these are processed by the compiler itself, not a preprocessor.

    %BEGIN LATEX
    \smallskip
    %END LATEX
    The following directives are recognised in the current version of \compiler:

    \dirdef{load}
    \lstinline|#load 'FILE'|
    \begin{cmdesc}
      Loads a header file.  \compiler{} looks first for \metavar{FILE}, then for
      \metavar{FILE}\file{.kh}, first in the same directory as the source file,
      and then in the \package{} library directory.  The contents of the file are
      parsed at the current position in the same way as C's \lstinline|#include|
      directive.
    \end{cmdesc}

    \dirdef{file}
    \lstinline|#file 'FILE'|
    \begin{cmdesc}
      Sets a default output filename.  This can be overridden on the \compiler{}
      command line with the \clopt{o} option.
    \end{cmdesc}

    \dirdef{target}
    \lstinline|#target|~\metavar{TARGET}
    \begin{cmdesc}
      Selects a default target; \metavar{TARGET} should be \file{RealLive},
      \file{AVG2000}, or \file{Kinetic}.  This can be overridden on the \compiler{}
      command line with the \clopt{t} option.  Note that the parameter is an
      identifier, not a string.
    \end{cmdesc}

    \dirdef{version}
    \lstinline|#version|~\metavar{A}\metaopt{.B\metaopt{.C\metaopt{.D}}}
    \begin{cmdesc}
      Selects a bytecode version to generate code for; this is the equivalent of
      the \clopt{f} command-line option, and functions identically.
    \end{cmdesc}

    \dirdef{resource}\index[concept]{resources!files}
    \lstinline|#resource 'FILE'|
    \begin{cmdesc}
      Loads the named resource file, providing access to all the strings it
      contains.  The scope of its definitions extends from the
      \lstinline|#resource| directive to the end of the file; it must precede
      any \lstinline|#res| directives referencing its contents.
    \end{cmdesc}

    \dirdef{base_res}\index[concept]{resources!files}
    \lstinline|#base_res 'FILE'|
    \begin{cmdesc}
      Loads the named resource file, providing access to all the strings it
      contains for use as a base of resources in a multi-version translation
	  project.  The scope of its definitions are limited to a resource file
	  previously loaded using a \lstinline|#resource| directive.
	  (New feature for version 1.45.)
    \end{cmdesc}

    \dirdef{res}\index[concept]{resources!strings}
    \lstinline|#res<|\metavar{ID}\lstinline|>|
    \begin{cmdesc}
      Inserts the resource string with the identifier \metavar{ID} at the
      current position.  See section \ref{sec:resources} for details.
    \end{cmdesc}

    \dirdef{entrypoint}
    \lstinline|#entrypoint|~\metavar{INDEX}
    \begin{cmdesc}
      Places an entrypoint at the current location in the code; entrypoints
      function as labels for the \fnref{jump} and \fnref{farcall} functions to
      jump into a scenario.  \metavar{INDEX} should be an integer between 0 and
      99 inclusive.

      If \metavar{INDEX} is 0, the directive is ignored.  Entrypoint 0 always
      comes at the very start of the scenario, and \compiler{} defines it
      automatically.  Superfluous entrypoint directives are accepted for
      compaitibility reasons.
    \end{cmdesc}

    \dirdef{character}
    \lstinline|#character 'NAME'|
    \begin{cmdesc}
      Adds \metavar{NAME} to the \textit{dramatis personae} table in the header
      of a bytecode file.  This is what \file{kprl -lN} reads.

      Character name data appears not actually to be used by \reallive; its
      purpose is a mystery, but it's probably just debug information.  It does
      not exist in \avgns, so the \lstinline|#character| directive is ignored
      when compiling for that target.
    \end{cmdesc}

    \dirdef{line}
    \lstinline|#line|~\metavar{LINE}
    \begin{cmdesc}
      Tells \compiler{} to start counting lines from the given value, rather than
      the actual line position in the source file.  May be of use if you want to
      preprocess code or use literate programming tools, but it's really only
      there to give the disassembler something to do when asked to read debug
      information.
    \end{cmdesc}

    \dirdef{kidoku\_type}
    \lstinline|#kidoku_type|~\metavar{TYPE}
    \begin{cmdesc}
      Determines the format to use for kidoku markers in generated bytecode. If
      the executable is to be run with \reallive\ 1.2.6.6 or later, this should
      usually be 2, although it appears not to be critical that this be the
      case; in all other cases it \emph{must} be left with its default value of
      1.

      Note that this is a global setting; the value that will be used for a
      given output file is that assigned most recently when the end of the file
      is reached.
    \end{cmdesc}

    \dirdef{print}
    \lstinline|#print|~\metavar{EXPR}
    \begin{cmdesc}
      Causes the compiler to print the current value of \metavar{EXPR} to stderr.
      \metavar{EXPR} must be a constant expression, but it can be an integer or
      a string.
    \end{cmdesc}

    \dirdef{warn}
    \lstinline|#warn|~\metavar{EXPR}
    \begin{cmdesc}
      As \dirref{print}, but the output is formatted as a compiler warning.
    \end{cmdesc}

    \dirdef{error}
    \lstinline|#error|~\metavar{EXPR}
    \begin{cmdesc}
      As \dirref{print}, but the output is formatted as a compiler error, and
      compilation is halted.
    \end{cmdesc}

  \lsubsection{Conditional compilation}

    The code to be compiled can be selected at compile-time by using a further
    set of directives.  As with the others, note that these are \emph{not}
    related to any sort of preprocessor.  They are block statements: they can
    only be used where a statement would be valid, and the code they enclose
    is analysed for syntactic validity even if it is not compiled.

    \dirdef{if}\dirdef{else}\dirdef{elseif}\dirdef{endif}
    \lstinline|#if|~\metavar{EXPR}\\
    \lstinline|#elseif|~\metavar{EXPR}\\
    \lstinline|#else|\\
    \lstinline|#endif|
    \begin{cmdesc}
      Select a block of code to compile based on the value of \metavar{EXPR}:

      \begin{lstlisting}
      #const First = gameexe('SEEN_START')
      #if First == 1
        #print 'The game begins with scenario 1'
        // Code for this case
      #elseif First == 2
        #print 'The game begins with scenario 2'
        // Code for this case
      #else
        #error "The game begins with scenario \i{First}, and I don't \ ^^
                 know what to do"
      #endif
      \end{lstlisting}

      Unlike \lstinline|:;| blocks, the contents of these directives are not
      counted as blocks for scoping purposes.
    \end{cmdesc}

    \dirdef{ifdef}\dirdef{ifndef}
    \lstinline|#ifdef|~\metavar{EXPR}\\
    \lstinline|#ifndef|~\metavar{EXPR}
    \begin{cmdesc}
      It is often convenient to be able to determine whether a given symbol has
      or has not been defined.  These two directives are shorthand ways to do
      this: they are exactly equivalent to \lstinline|#if|, except that every
      identifier in \metavar{EXPR} that is not directly compared with anything
      else is replaced with a call to the \fnref{defined?} macro.

      \begin{lstlisting}
      #ifndef foo && bar && baz > 1 // -> #if !defined?(foo) && !defined?(bar) && baz > 1
        {- do stuff -}
      #endif
      \end{lstlisting}
    \end{cmdesc}

  \lsubsection{Control structures}

    \index{if}\index{else}
    \noindent\lstinline|if|~\metavar{CONDITION}~\metavar{STATEMENT}\\
    \lstinline|if|~\metavar{CONDITION}~\metavar{STATEMENT}~\lstinline|else|~\metavar{STATEMENT}
    \begin{cmdesc}
      A standard conditional control structure.  \metavar{CONDITION} is evaluated;
      if the result is non-zero, \metavar{STATEMENT} is executed.  The
      optional \lstinline|else| allows a statement to be specified for execution
      if the condition evaluates to zero.

      Kepago adopts the usual rule to resolve the `dangling
      \lstinline|else|' problem: each \lstinline|else| is taken to apply to the
      innermost available \lstinline|if|.  This can be overridden by use of blocks:

      \begin{lstlisting}
      if rnd(10) < 5:
        if SyscomEnabled, 'your code here';
      else
        'Without the :; above, this would attach to \ ^^
         the inner `if\'.'
      \end{lstlisting}
    \end{cmdesc}

    \index{while}
    \noindent\lstinline|while|~\metavar{CONDITION}~\metavar{STATEMENT}
    \begin{cmdesc}
      If the value of \metavar{CONDITION} is non-zero, \metavar{STATEMENT}
      is executed repeatedly; \metavar{CONDITION} is checked after each
      iteration, and the loop exits when it evaluates to zero.

      You can exit the loop prematurely with the \lstinline|break|
      statement, or jump straight to the next iteration with the
      \lstinline|continue| statement.
    \end{cmdesc}

    \index{repeat}\index{till}
    \noindent\lstinline|repeat|~\metavar{STATEMENTS}~\lstinline|till|~\metavar{CONDITION}
    \begin{cmdesc}
      The opposite of \lstinline|while|.  \metavar{STATEMENTS} is executed
      at least once, and the loop continues for as long as \metavar{CONDITION}
      is zero.

      For historical reasons, and unlike the other structures in this section,
      the \lstinline|repeat| loop is a block in itself: you can include multiple
      statements without a \lstinline|:;| block.
    \end{cmdesc}

    \index{for}
    \noindent\lstinline|for (|\metavar{INITIALISATION}\lstinline|) (|\metavar{CONDITION}\lstinline|) (|\metavar{INCREMENT}\lstinline|)|~\metavar{STATEMENT}
    \begin{cmdesc}
      A C-style `for' loop.

      \begin{lstlisting}
      for (int i = 0) (i < 10) (i += 1):
        do_stuff(i);
      \end{lstlisting}
      \noindent
      is equivalent to
      \begin{lstlisting}
      : int i = 0
        while i < 10:
          do_stuff(i)
          i += 1;;
      \end{lstlisting}
    \end{cmdesc}

    \index{case}\index{of}\index{other}\index{ecase}
    \noindent\lstinline|case|~\metavar{EXPR}\\
    \lstinline|of|~\metavar{CASE}\\
    \lstinline|other|\\
    \lstinline|ecase|
    \begin{cmdesc}
      \metavar{EXPR} is compared to each \metavar{CASE} in turn; if a match is 
      found, the following code is executed.  The \lstinline|other| clause is 
      equivalent to an \lstinline|of| clause, but always matches; it is 
      optional, and if present must be the last clause.

      As with C's `switch' statement, each case should be terminated with a
      \lstinline|break| statement, or execution will fall through to the next
      case.  This is useful where multiple values require the same treatment:

      \begin{lstlisting}
      int qual = SoundQuality
      'Sound mode is '
      if qual % 2, '16-bit ' else '8-bit '
      case qual
      of 0
      of 1
        '11 kHz'
        break
      of 2
      of 3
        '22 kHz'
        break
      of 4
      of 5
        '44 kHz'
        break
      other
        '48 kHz'
      ecase
      pause
      \end{lstlisting}
      
      \compiler{} will attempt to optimise the test and jumps away if 
      \metavar{EXPR} can be evaluated at compile-time.  In certain cases it may 
      be desirable to know whether this optimisation has succeeded (for example, 
      when writing \lstinline|other| clauses that raise an error, you may wish 
      to raise the error at compile-time in such cases).  \compiler{} therefore 
      defines the symbol \lstinline|__ConstantCase__| when compiling 
      \lstinline|case| blocks; if it is non-zero, then the innermost case block 
      currently being compiled has been optimised away.      
    \end{cmdesc}

  \lsubsection{Function calls}\label{sec:functioncalls}

    With one or two exceptions, function calls use the standard C-like syntax:
    the function name followed by a list of parameters, bracketed and
    comma-delimited.

    Anything valid on the right-hand side of an assignment expression is also
    valid as a function parameter.  Certain functions permit other constructs,
    such as tuples (parameters containing multiple expressions; in Kepago these
    are enclosed in curly braces), and one or two have wholly different
    syntaxes.  All these exceptions are documented under the appropriate
    function in chapter \ref{chapter:functions}.

    \index{op$<>$}
    \lsubsubsection{Unknown functions}

      It may sometimes be desirable to make use of a function that exists in
      \reallive\ but is not currently exposed through the Kepago/\reallive{}
      API\@. There exists a `raw opcode' command that can be used to insert such
      functions: it has the format `\lstinline|op<|\metavar{type}\lstinline|:|%
      \metavar{module}\lstinline|:|\metavar{opcode}\lstinline|, |%
      \metavar{overload}\lstinline|>|', which can be followed with a
      parenthesised parameter list as any function (but cannot be used in
      assignments).  The variables are all integers; \metavar{type} and
      \metavar{module} appear to be used to identify groups of related
      functions, \metavar{opcode} identifies a particular function (its value is
      only unique within a particular type/module combination), and finally
      \metavar{overload} identifies an instance of that opcode (different
      instances have the same broad semantics, but take varying numbers of
      parameters).

      Mnemonic aliases are defined for some values of \metavar{module}, in the
      hope that this may give some hint as to the purpose of an unknown function
      when \archiver{} disassembles a scenario containing it.  For example, the
      \fnrefnoparens{pause} function can also be invoked with
      \lstinline|op<0:Msg:00017, 0>|.

      In the general case, however, it is preferable to add support for the
      function to the API than to use it with \lstinline|op<>|.  This can be
      accomplished by editing \file{reallive.kfn}, or more easily by providing
      the author with an example and description, upon which he'll happily do it
      for you.

\lsection{String handling}\label{sec:strings}

  Strings can be delimited with either \lstinline|'| or \lstinline|"|; there is
  no semantic difference between the two.  Due to the limitations of the
  \reallive\ system itself, only JIS characters are valid in strings. To use
  within a string a quote of the type being used to delimit that string, it must
  be escaped with a backslash; line breaks must also be escaped, and any
  whitespace at the start of the following line will be ignored, unless this too
  is escaped:
  \begin{lstlisting}
    str s = "This string's value \ ^^
             is a single line, spaced\ ^^
           \ normally.")
  \end{lstlisting}

  Note however that arbitrary characters may not be escaped: any escaped
  alphabetic character is taken to open a control code, as will an escaped left
  brace.

  \lsubsection{Displaying text}

    Display strings (that is, strings used directly as statements, rather than
    in expressions) are passed directly to \reallive's text display routines.
    When one is encountered, a text window of the currently active type is
    opened and the text printed in it.  (Text window types are defined in
    \gameexe, as described in \ref{sec:windowdefinition}, and selected with the
    \fnref{TextWindow} function.)

  \lsubsection{Usable characters}\label{sec:encodings}

    The \reallive\ bytecode format requires all textual data to be in the 
    Shift\_JIS encoding.  By default, therefore, \package\ converts text to 
    Shift\_JIS: it follows that the only characters which are valid in Kepago 
    strings are those in the JIS~X~0201 or JIS~X~0208 character sets. This is 
    perfect for Japanese text, and sufficient for most English.
    
    Other languages require characters not present in the JIS character sets. 
    There are two solutions to this issue.  One is to fake the required 
    characters: some glyphs can be included as bitmaps with \ccref{em}, others 
    (such as accented letters) can be built up through overprinting by using 
    \ccref{mv}. A better solution\,\textemdash\,in some cases, such as Chinese, the 
    \emph{only} solution\,\textemdash\,is to use a non-JIS character set, with a 
    non-standard encoding that has the same characteristics as Shift\_JIS, and to 
    arrange for this to be decoded on the fly in an intermediate layer between 
    RealLive and the operating system.
    
    In \package, this is accomplished in three stages:
    
    First, the UTF-8 encoding should be used for source code files.  This is the 
    only supported input encoding that can handle non-Japanese text.  If it is
    not the default encoding for your copy of \package, you will have to specify
    the option "\texttt{-e utf8}" when compiling the code.
    
    Second, an \emph{output encoding transformation} is applied.  This is done 
    by passing the "\texttt{-x} \metavar{ENC}" option when compiling the code, 
    where \metavar{ENC} is the name of a supported transformation (see below).
    
    The final step is to arrange for the \reallive\ interpreter to be able to 
    decode the transformed text.  This can be done either by modifying the 
    interpreter itself, or by using an extension DLL to hook into it at 
    runtime.  A suitable DLL is provided in the form of the rlBabel library
    (see \ref{lib:rlBabel}).
    
    \package\ currently supports the following transformations:
    
    \begin{nicelist}
    \item[None]
      For Japanese or ASCII text. This is the default.
    \item[Chinese]
      For Simplified Chinese text. The output uses a non-standard encoding of 
      the GB2312 character set (based on a system formerly used by the Key Fans Club).
    \item[Korean]
      For Korean text. The output uses a non-standard encoding and character set.
      The characters encoded comprise the non-hanja parts of KS~X~1001, plus the
      4000-odd additional precomposed hangul from the ill-fated Unicode 1.1: this 
      appears to be the simplest practical compromise for encoding modern Korean
      text, though the encoding could potentially be expanded further if necessary.
    \item[Western]
      For Western European text. The output uses a non-standard encoding of
      the Windows CP1252 character set (ISO-8859-1 with extensions).
      
      Since this encoding uses double-byte characters to represent some 
      half-width characters, it should be used with the rlBabel lineation 
      library (\ref{lib:rlBabel:lineation}) to ensure correct character spacing.      
    \end{nicelist}

  \lsubsection{Control codes}\index[concept]{control codes}

    Control code syntax is \TeX-style, \lstinline|\|\metavar{identifier}%
    \rawlbrace\lstinline|}|, where what goes between the curly braces has the
    same syntax as the contents of the parentheses in a normal function
    call\,\textemdash\,in most cases the braces are either empty or contain a
    single integer or variable.  Note that for control codes of more than one
    letter, braces are always required, even if no parameters are being passed
    to the code.

    Descriptions of the basic control codes currently available follow.  In
    addition to these, there are also more complex codes \ccref{name} and
    \ccref{g}, described in the following subsections, and a set of control
    codes only valid in resource files, described in section
    \ref{sec:resources}.

    \ccdef{n}
    \lstinline|\n|
    \begin{cmdesc}
      Forces a line break at the current position, retaining indentation.
    \end{cmdesc}
    \ccdef{r}
    \lstinline|\r|
    \begin{cmdesc}
      Forces a line break at the current position, resetting indentation.
    \end{cmdesc}
    \ccdef{p}
    \lstinline|\p|
    \begin{cmdesc}
      Inserts a pause.  Text display will halt until the player clicks to
      advance, but it will then continue where it left off, without clearing the
      screen.
    \end{cmdesc}
    \ccdef{wait}
    \lstinline|\wait|\rawlbrace\metavar{time}\lstinline|}|
    \begin{cmdesc}
      Pauses \metavar{time} ms before continuing to print text.
    \end{cmdesc}
    \ccdef{m}\ccdef{l}\index[concept]{variables!name variables}\index[concept]{name variables}
    \lstinline|\m|\rawlbrace\metavar{name}\lstinline|}|\\
    \lstinline|\l|\rawlbrace\metavar{name}\lstinline|}|
    \begin{cmdesc}
      Inserts the value of a name variable: \ccref{m} for global names, and
      \ccref{l} for local names.  \metavar{name} can be either an integer
      (the index of the variable, as used in calls to the \fnref{GetName}
      family) or one or two alphabetic characters (`A' to 'ZZ', as used in
      the \ivarref{NAME} variables in \gameexe).  See \ref{sec:namevars} for
      details of name variables.

      A second argument may optionally be supplied, which should be a constant
      integer.  If this is given, it identifies a single character of the name
      to be printed (zero-indexed).
    \end{cmdesc}
    \ccdef{i}
    \lstinline|\i|\rawlbrace\metavar{int}\lstinline|}|
    \begin{cmdesc}
      Displays the value of \metavar{int}, which can be an arbitrary integer
      expression.

      You may optionally supply a minimum length, of the format
      \lstinline|\i:|\metavar{length}\rawlbrace\metavar{int}\lstinline|}|; if
      this is supplied, the number will be left-padded with zeroes to ensure
      that it is always at least \metavar{length} digits.
    \end{cmdesc}
    \ccdef{s}
    \lstinline|\s|\rawlbrace\metavar{str}\lstinline|}|
    \begin{cmdesc}
      Displays the value of the string variable \metavar{str}.
    \end{cmdesc}
    \ccdef{size}
    \lstinline|\size|\rawlbrace\metaopt{pixels}\lstinline|}|
    \begin{cmdesc}
      \metavar{pixels} is optional.  If it is given, the font size will be set
      to that size; if it is not, the font size will be reset to the default.
    \end{cmdesc}
    \ccdef{c}\fnidx{FontColour}
    \lstinline|\c|\rawlbrace\metavar{idx}\lstinline|, |\metaopt{bg\_idx}\lstinline|}|
    \begin{cmdesc}
      Sets the colour of the following text.  The values are indices to the
      game's palette, which is defined in \gameexe{} with the
      \ivarref[COLOR:TABLE]{COLOR\_TABLE} command.  \ccref{c} can also be used
      without any arguments, which resets the colours to their defaults.

      For example, if \inivar{COLOR\_TABLE.001} were red and
      \inivar{COLOR\_TABLE.002} were green, someone addicted to pointless
      examples could write
      \begin{lstlisting}
      'I like using \c{1}red\c{} text, and sometimes \ ^^
       \c{1, 2}red with a green shadow\c{}.'
      \end{lstlisting}

      This control code behaves in the same way as the \fnref{FontColour}
      function: the colour will be reset automatically at the end of the
      string.  If you want to set multiple strings in the same non-default
      colour, you will have to use \ccref{c} at the start of all of them.
    \end{cmdesc}
    \ccdef{ruby}\index[concept]{glosses}
    \lstinline|\ruby|\rawlbrace\metavar{text}\lstinline|}=|\rawlbrace\metavar{gloss}\lstinline|}|
    \begin{cmdesc}
      Used to display interlinear glosses or ruby, also known as
      \textit{furigana}.  \metavar{text} will be displayed normally, with
      \metavar{gloss} printed above it in small type.

      You must set the \ivarref[WINDOW.LUBY:SIZE]{WINDOW.LUBY\_SIZE}
      \emph{(sic)} variable for the current window to an appropriate size in
      order to use this control code.
    \end{cmdesc}
    \ccdef{e}\ccdef{em}\index[concept]{e-moji}\index[concept]{bitmapped characters}
    \lstinline|\e|\rawlbrace\metavar{index}\lstinline|,|~\metaopt{size}\lstinline|}|\\
    \lstinline|\em|\rawlbrace\ldots\lstinline|}|
    \begin{cmdesc}
      Prints a bitmapped character or icon at the current point in the text.
      \ccref{e} prints the bitmap in full colour;  \ccref{em} takes its alpha channel
      and displays that in the current font colour.

      Bitmaps are drawn from files defined with the \ivarref[E:MOJI]{E\_MOJI}
      settings in \gameexe.  You must define at least \inivar{E\_MOJI.000} in order to
      use these codes.  If multiple files are defined, they should contain the
      same characters at different sizes.

      The bitmap used is always the largest available that is in height smaller
      than or equal to the current font size; if no matching bitmap is
      available, a space is left.  The optional \metavar{size} argument can be
      used to force the font size to a particular size temporarily, to select a
      particular size manually.  Note however that in the current implementation
      it also resets the font size to the window's default - you will have to
      follow it with a \ccref{size} code if you were working at a different
      size.
    \end{cmdesc}

    \ccdef{mv}\ccdef{mvx}\ccdef{mvy}
    \lstinline|\mv|\rawlbrace\metavar{x}\lstinline|, |~\metavar{y}\lstinline|}|\\
    \lstinline|\mvx|\rawlbrace\metavar{x}\lstinline|}|\\
    \lstinline|\mvy|\rawlbrace\metavar{y}\lstinline|}|
    \begin{cmdesc}
      Move the insertion point (i.e.\ the offset of the next character) by $(x, y)$
      pixels.
      
      If the new offset is beyond the right-hand margin of the text window, the text
      will automatically wrap, effectively placing it at the start of the next line
      instead.  Other margins are not checked, but text will always be clipped to the
      window margins; you can place text above or to the left of the window, but only
      those parts of letters within the margins will be displayed.
      
      There are three major uses for these codes.  The first is character composition
      by overprinting:
      \begin{lstlisting}[escapechar=@]
        #const cw = gameexe('WINDOW.000.MOJI_SIZE') / 2
                  + gameexe('WINDOW.000.MOJI_REP', 0) / 2
        'A t^\mvx{-cw}ete-`\mvx{-cw}a-t^\mvx{-cw}ete with Sayuri'
        page
      \end{lstlisting}
      \noindent displays ``a t\^ete-\`a-t\^ete with Sayuri'' fairly reliably, 
      even though the accented characters do not exist in most Japanese fonts. 
      (Note the code that calculates the width in pixels of a Latin character
      - this would need modifying if you were not printing to window 0, or not
      using the default font size.)
      
      The second use is printing superscript and subscript text:
      \begin{lstlisting}[escapechar=@]
        '\size{26}x\size{16}\mvy{-1}2\mvy{1}\size{26}' // x^{2}
        ' +\mvx{8}'                                    // +
        'log\mv{1,13}\size{18}16\size{26}\mv{6,-13}y'  // \log_{16} y
        '\mvx{8}=\mvx{8}z\size{}'                      // = z
        page
      \end{lstlisting}
      \noindent displays a reasonably nicely spaced version of ``$x^{2} + 
      \log_{16} y = z$'' in most fonts (observe the use of \lstinline|\mvx{8}| 
      to insert a narrower-than-usual space).
      
      The final use is printing non-square bitmapped characters: 
      \lstinline|'\e{0}\mvx{-4}'| would be a suitable way to display a bitmap 
      containing a character four pixels narrower than the font height.
      
      These codes are also used by the rlBabel DLL to implement proportional
      text output (see \ref{lib:rlBabel:lineation} and the rlBabel source code
      for implementation details).
    \end{cmdesc}

    \ccdef{pos}\ccdef{posx}\ccdef{posy}
    \lstinline|\pos|\rawlbrace\metavar{x}\lstinline|, |~\metavar{y}\lstinline|}|\\
    \lstinline|\posx|\rawlbrace\metavar{x}\lstinline|}|\\
    \lstinline|\posy|\rawlbrace\metavar{y}\lstinline|}|
    \begin{cmdesc}
      As \ccref{mv} etc., except that the coordinates are interpreted as 
      absolute offsets from the origin, rather than relative to the current 
      insertion point.      
    \end{cmdesc}

    \ccdef{ind}
    \lstinline|\ind|\rawlbrace\metaopt{pixels}\lstinline|}|
    \begin{cmdesc}
      \metavar{pixels} is optional.  If it is given, indentation will be set
      to that value; if it is not, indentation will be reset to the default.
    \end{cmdesc}

    \ccdef{noind}
    \lstinline|\noind|
    \begin{cmdesc}
      Reset indentation.
    \end{cmdesc}

    \ccdef{shake}
    \lstinline|\shake|\rawlbrace\metavar{index}\lstinline|}|
    \begin{cmdesc}
      Shakes the screen, using the movements defined in \gameexe\ with the
  variable @iref{SHAKE}.\metavar{index}. \ivarref[SHAKE]{SHAKE}.\metavar{index}.
  
  \metavar{pixels} is optional.  If it is given, indentation will be set
      to that value; if it is not, indentation will be reset to the default.
    \end{cmdesc}

  \lsubsection{Names}\label{sec:nameblocks}\maketarget{ccode}{name}\ccidx{name}\index[concept]{names}
    As display strings are normally used for game text, \reallive\ naturally
    provides means for identifying character names.  This is accomplished
    with the \ccref{name} control code.

    The format of this code is
    \lstinline|\|\rawlbrace\metavar{text}\lstinline|}|.  \metavar{text} is
    arbitrary text, which is used as the current character name.

    Note two unique features of this code.  Firstly, it has no identifier; you
    can use \lstinline|\name{}| as well, but \lstinline|\{}| is the canonical
    form.  This is just to save typing, as this is the most common control code.
    Secondly, \emph{if it is followed by a space, that is gobbled}.  This
    permits you to write \lstinline|'\{Foo} "..."'|, and have it appear correctly
    spaced in the output.  If you actually wanted a space after the name, escape
    it with another backslash: \lstinline|'\{Foo}\ "..."'|.  (You probably won't
    like the results.)

    The effect this has is can be controlled to a great extent by settings in
    \gameexe.  If \ivarref[WINDOW.NAME:MOD]{WINDOW.NAME\_MOD} is non-zero for
    the current window style, the name will be displayed in a separate smaller
    window, based on the other \ivarref{WINDOW.NAME} settings.  If
    \ivarref[WINDOW.NAME:MOD]{WINDOW.NAME\_MOD} is zero, the name will be
    printed inline at the current position, and followed with a space; in this
    latter case, if \ivarref[WINDOW.INDENT:USE]{WINDOW.INDENT\_USE} is non-zero,
    an indent point will then be set at the new $x$ offset in the text window,
    meaning that subsequent lines of text will begin at that offset.

    A separate but related topic is the use of name variables to store
    customisable character names.  As described in section \ref{sec:namevars},
    these can be referenced directly from within display strings with the
    \ccref{l} and \ccref{m} control codes.  For example, a common idiom to set
    the speaker name to the player is the code \lstinline|\{\m{A}}|.

  \lsubsection{Glosses}\maketarget{ccode}{g}\ccidx{g}\index[concept]{hypertext}\index[concept]{glosses}

    Kepago provides for hypertext glosses using a control code \lstinline|\g|.
    The syntax is
    \lstinline|\g|\rawlbrace\metavar{text}\lstinline|}=|\rawlbrace\metavar{gloss}\lstinline|}|.
    \metavar{text} is arbitrary text, which is always output in the normal way,
    and may be highlighted in some way.  When it is clicked on, the value of
    \metavar{gloss} is passed as a string to a handler routine, which would
    typically display it in a subsidiary window.

    Support for these is limited in \compiler.  The control code is always
    accepted, but it is only processed when the rlBabel library is in use for
    dynamic lineation (see \ref{lib:rlBabel:lineation}); in all other cases,
    \metavar{text} is simply displayed as normal text.

  \lsubsection{Lineation}\label{sec:lineation}\index[concept]{lineation}

    Since the \reallive\ system is designed for use with Japanese only, it does
    not implement the more complex line breaking logic required for Western
    languages.  In Japanese, it is acceptable to break a line anywhere,
    including in the middle of words, so this is the behaviour \reallive{}
    adopts.  This makes it necessary to implement lineation specially for
    Western text.

    Versions of \package\ up to 1.03 implemented static lineation.  Since this 
    is impossible to do correctly, however, this feature has been removed and 
    replaced with various dynamic lineation techniques, which ensure that text 
    is always correctly lineated even in the presence of variable-length 
    elements.  These are implemented as libraries, and disabled by default; see 
    section \ref{libs:extra} for usage details.

\lsection{Resource files and resource strings}\label{sec:resources}\index[concept]{resources!files}

  It can often be desirable to separate program logic from the game's script;
  for example, if one is releasing a game in several languages, it is more
  convenient to provide translators with just the text, while if one is
  releasing versions of the same game with different code (for example, adult
  and all-age versions) it can be convenient to be able to use the same script
  with both.  Resource files provide a simple means of accomplishing this.

  \lsubsection{Resource file syntax}\index[concept]{resources!strings}

    A resource file is basically an association table of keys to strings.

    A key is defined by enclosing it in angle brackets.  Keys can contain any
    combination of characters, with a few restrictions.  Firstly, purely
    numerical keys are treated as numbers: \lstinline|<$00d>| identifies the
    same string as \lstinline|<13>| and \lstinline|<0013>|.  Secondly, keys may
    not contain spaces, line breaks, or the characters \lstinline|>| and
    \lstinline|}|.  Both of these restrictions can be worked round by quoting
    the key; such a key uses the normal string literal syntax, can contain any
    character, and distinguishes between different representations of integers.

    Each occurrence of a key begins a new string; the text between it and the
    next key or the end of the file is interpreted as a resource string.  The
    syntax of a resource string is broadly similar to that of a display string
    literal (see section \ref{sec:strings}), with a few exceptions:
    \begin{itemize}
    \item
      The literal character \lstinline|<| must be written \lstinline|\<|.
    \item
      Kepago comments are parsed, so literal \lstinline|//| must be written
      \lstinline|\//| and literal \ifhevea\texttt{\{-}\else\lstinline|{-|\fi{}
      must be written \ifhevea\texttt{\{$\backslash$-}\else\lstinline|{\-|\fi{}.
      For block comments, note that control codes take precedence: that is to
      say, \lstinline|\{-| will be interpreted as the opening of a name block
      (see \ref{sec:nameblocks}) that begins with a \lstinline|-| character, and
      \lstinline|\i{-1-}{1}| will raise a syntax error, since it will be interpreted
      as \lstinline|\i{ -1 - }| followed by the text \lstinline|{1}|, and Kepago
      requires a right-hand side to what is being read as a subtraction operator.
    \item
      Quotes are always treated as literal characters, and never need
      escaping.
    \item
      Line breaks do not need escaping; however, any whitespace before an
      unescaped line break will be trimmed,\footnote{\LaTeX{} users may expect
      spacing to be automatic, but the syntactic similarities to \LaTeX{} are
      coincidental; `and!the', where the ! is a line break, will produce
      `andthe', not `and the'.} so you can escape the line break to preserve
      it.  Alternatively, \lstinline|\_| can be used to represent a
      non-trimmable space.
%    \item\label{item:resglosses}
%      Where gloss codes (\ccref{g}) are used in a resource string, and the
%      gloss text is given as a resource string key, the key can be left empty:
%      for example, it is legal to write \lstinline|\g{foo}=<>|.  This creates
%      an anonymous reference which will be resolved by using the next resource
%      string in the file.  It is possible to have multiple anonymous
%      references in one string: see subsection \ref{sec:anonrefs} for details
%      of how this case is resolved.
    \end{itemize}

  \lsubsection{Additional control codes}\index[concept]{control codes}

    There are also some additional control codes that can be used in resource
    strings.

    \ccdef{d}
    \lstinline|\d|
    \begin{cmdesc}
      Where two versions of a script are being produced, and one requires
      fewer strings than the base version, you can use \ccref{d} to remove
      superfluous strings without modifying the Kepago source code.

      The resource string becomes a `remove string' command; referencing it
      will remove the reference, and if it is referenced by a display string
      command that is followed by a \fnref{pause} call, the pause will also be
      removed.
    \end{cmdesc}
    \ccdef{a}
    \lstinline|\a|\rawlbrace\metaopt{str}\lstinline|}|
    \begin{cmdesc}
      Where two versions of a script are being produced, and one requires
      more strings than the base version, you can use \ccref{a} to add extra
      strings without modifying the Kepago source code.

      The current resource string is processed as normal, but when it is
      referenced by a display string command, the resource string
      \lstinline|<|\metavar{str}\lstinline|>| will be added after it as
      another display string command; if the referencing command was followed
      by a \fnref{pause} call, another \fnref{pause} will be added after the
      new string.  If multiple \ccref{a} codes appear in one resource string,
      the extra strings will be added in the order of the \ccref{a} codes.

      \metavar{str} is optional.  If it is not given (an `anonymous
      reference'), the next string in the resource file will be used; see
      \ref{sec:anonrefs} below for how multiple anonymous references are
      resolved.
    \end{cmdesc}
    \ccdef{res}
    \lstinline|\res|
    \lstinline|\res|\rawlbrace\metavar{ID}\lstinline|}|
    \begin{cmdesc}
      Where multiple versions of a script are being produced, where a variant
	  contains many strings in common with a base version and the resource ids
	  vary from base to variant, it may simplify a things considerably to inherit 
	  common resource strings from the base. 
	  
	  You can use \ccref{res} to specify the id of a resource string to inherit
	  from a base resource file loaded using a \dirref{base_res} directive in 
	  the Kepago script file.
	  
	  If no \dirref{base_res} directive was used, ids refer to strings within the
	  current resource file.
    \end{cmdesc}

  \lsubsection{Anonymous references}\label{sec:anonrefs}\index[concept]{resources!anonymous references}

    If multiple anonymous references are given in a single string, they are
    resolved sequentially and recursively: that is, anonymous references
    within a string referenced anonymously are resolved \emph{before} any
    further anonymous references in the original string.

    An example may make this clearer:
    \begin{lstlisting}[basicstyle=\ttfamily,stringstyle=\color{black}]
      <foo>
        This is foo.\a\a
      <bar>
        This is bar.\a
      <baz>
        This is baz.
      <quux>
        This is quux.
    \end{lstlisting}
    This is equivalent to writing
    \begin{lstlisting}[basicstyle=\ttfamily,stringstyle=\color{black}]
      <foo>
        This is foo.\a{bar}\a{quux}
      <bar>
        This is bar.\a{baz}
      <baz>
        This is baz.
      <quux>
        This is quux.
    \end{lstlisting}
    Note how the second \ccref{a} in \lstinline|<foo>| resolves to
    \lstinline|<quux>|, because \lstinline|<baz>| has been taken by the
    \ccref{a} in \lstinline|<bar>|.

    Resource strings for use with anonymous references can be anonymous
    themselves: that is, you could also write
    \begin{lstlisting}[basicstyle=\ttfamily,stringstyle=\color{black}]
      <foo>
        This is foo.\a
      <>
        This is anonymous.
    \end{lstlisting}
    This can be clearer to read, and has the advantage that anonymous
    resource strings normally generate an error, so you will be able to
    tell whether you have included the correct number.

  \lsubsection{Using resource strings}

    To load a resource file and make the strings it contains available to your
    code, use the \dirref{resource} directive at the start of the Kepago source
    file.

    To reference a resource string, use the \dirref{res} directive with the key
    of the string you wish to include.

    To load a base resource file and make the strings it contains available to
	your code, use the \dirref{resource} directive at the start of the Kepago 
	source file.

    To reference a base resource string within a resource file, use a \ccref{res}
	control code with the key of the base resource string you wish to include.

