Merge "Update antlr to 3.5.2" am: 023edee1e8
am: d522258e22

Change-Id: I642436a6fcbd5bf16b6e64c22638e4f061244832
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..cceb80d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,30 @@
+# Maven build folders
+target/
+
+# IntelliJ project files
+*.iml
+*.ipr
+*.iws
+.idea/
+
+# Eclipse project files
+.project
+.classpath
+.settings/
+
+# NetBeans user configuration
+nbactions.xml
+nb-configuration.xml
+
+# Python runtime files
+*.py[co]
+
+# ANTLR C# target build folders
+/runtime/CSharp3/Sources/Antlr3.Runtime/bin/
+/runtime/CSharp3/Sources/Antlr3.Runtime/obj/
+/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/bin/
+/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/obj/
+/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/bin/
+/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/obj/
+/runtime/CSharp3/Sources/Antlr3.Runtime.Test/bin/
+/runtime/CSharp3/Sources/Antlr3.Runtime.Test/obj/
diff --git a/BUILD.txt b/BUILD.txt
index f6e41c3..d0d1b16 100644
--- a/BUILD.txt
+++ b/BUILD.txt
@@ -1,493 +1,6 @@
- [The "BSD license"]
- Copyright (c) 2010 Terence Parr
- Maven Plugin - Copyright (c) 2009      Jim Idle
+We have moved instructions for building ANTLR with the maven build system to:
 
- All rights reserved.
+http://www.antlr.org/wiki/display/ANTLR3/Building+ANTLR+with+Maven
 
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
- 3. The name of the author may not be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-============================================================================
-
-This file contains the build instructions for the ANTLR toolset as
-of version 3.1.3 and beyond.
-
-The ANTLR toolset must be built using the Maven build system as
-this build system updates the version numbers and controls the
-whole build process. However, if you just want the latest build
-and do not care to learn anything about Maven, then visit the 'target'
-directories (for jars) under the depot mirror root here:
-
-   http://antlr.org/depot
-
-If you are looking for the latest released version of ANTLR, then
-visit the downloads page on the main antlr.org website.
-
-These instructions are mainly for the ANTLR development team,
-though you are free to build ANTLR yourself of course.
-
-Source code Structure
------------------------
-
-The main development branch of ANTLR is stored within the Perforce SCM at:
-
-   //depot/code/antlr/main/...
-
-release branches are stored in Perforce like so:
-
-   //depot/code/antlr/release-3.1.3/...
-
-In this top level directory, you will find a master build file for
-Maven called pom.xml and you will also note that there are a number of
-subdirectories:
-
- tool                  - The ANTLR tool itself
- runtime/Java          - The ANTLR Java runtime
- runtime/X             - The runtime for language target X
- gunit                 - The grammar test tool
- antlr3-maven-plugin   - The plugin tool for Maven allowing Maven
- 		          projects to process ANTLR grammars.
-
-Each of these sub-directories also contains a file pom.xml that
-controls the build of each sub-component (or module in Maven
-parlance).
-
-Build Parameters
------------------
-
-Alongside each pom.xml (other than for the antlr3-maven-plugin), you
-will see that there is a file called antlr.config. This file is called
-a filter and should contain a set of key/value pairs in the same
-manner as Java properties files:
-
-antlr.something="Some config thang!"
-
-When the build of any component happens, any values in the
-antlr.config for the master build file and any values in the
-antlr.config file for each component are made available to the
-build. This is mainly used by the resource processor, which will
-filter any file it finds under: src/main/resources/** and replace any
-references such as ${antlr.something} with the actual value at the
-time of the build.
-
-Building
---------
-
-Building ANTLR is trivial, assuming that you have loaded Maven version
-3.0.3 or better on to your build system and installed it as explained
-here:
-
-http://maven.apache.org/download.html
-
-Note that the ANTLR toolset will ONLY build with version 3.0.3 of Maven
-as of release 3.4.
-
-If you are unfamiliar with Maven (and even if you are), the best
-resource for learning about it is The Definitive Guide:
-
-http://www.sonatype.com/books/maven-book/reference/public-book.html
-
-The instructions here assume that Maven is installed and working correctly.
-
-If this is the first time you have built the ANTLR toolset, you will
-possibly need to install the master pom in your local repository
-(however the build may be able to locate this in the ANTLR snapshot or
-release repository). If you try to build sub-modules on their own (as
-in run the mvn command in the sub directory for that tool, such as
-runtime/Java), and you receive a message that maven cannot find the
-master pom, then execute this in the main (or release) directory:
-
-mvn -N install
-
-This command will install the master build pom in your local maven
-repository (it's ~/.m2 on UNIX) and individual builds of sub-modules
-will now work correctly.
-
-To build then, simply cd into the master build directory
-(e.g. $P4ROOT//code/antlr/main) and type:
-
-mvn -Dmaven.test.skip=true
-
-Assuming that everything is correctly installed and synchronized, then
-ANTLR will build and skip any unit tests in the modules (the ANTLR
-tool tests can take a long time).
-
-This command will build each of the tools in the correct order and
-will create the jar artifacts of all the components in your local
-development Maven repository (which takes precedence over remote
-repositories by default). At the end of the build you should see:
-
-[INFO] ------------------------------------------------------------------------
-[INFO] Reactor Summary:
-[INFO] ------------------------------------------------------------------------
-[INFO] ANTLR Master build control POM ........................ SUCCESS [1.373s]
-[INFO] Antlr 3 Runtime ....................................... SUCCESS [0.879s]
-[INFO] ANTLR Grammar Tool .................................... SUCCESS [5.431s]
-[INFO] Maven plugin for ANTLR V3 ............................. SUCCESS [1.277s]
-[INFO] ANTLR gUnit ........................................... SUCCESS [1.566s]
-[INFO] Maven plugin for gUnit ANTLR V3 ....................... SUCCESS [0.079s]
-[INFO] ------------------------------------------------------------------------
-[INFO] ------------------------------------------------------------------------
-[INFO] BUILD SUCCESSFUL
-[INFO] ------------------------------------------------------------------------
-[INFO] Total time: 11 seconds
-
-However, unless you are using Maven exclusively in your projects, you
-will most likely want to build the ANTLR Uber Jar, which is an
-executable jar containing all the components that ANTLR needs to build
-and run parsers (note that at runtime, you need only the runtime
-components you use, such as the Java runtime and say stringtemplate).
-
-Because the Uber jar is not something we want to deploy to Maven
-repositories it is built with a special invocation of Maven:
-
-mvn -Dmaven.test.skip=true package assembly:assembly
-
-Note that Maven will appear to build everything twice, which is a
-quirk of how it calculates the dependencies and makes sure it has
-everything packaged up so it can build the uber-jar assembly.
-
-Somewhere in the build output (towards the end), you will find a line
-like this:
-
-[INFO] Building jar: /home/jimi/antlrsrc/code/antlr/main/target/antlr-master-3.4-SNAPSHOT-completejar.jar
-
-This is the executable jar that you need and you can either copy it
-somewhere or, like me, you can create this script (assuming UNIX)
-somewhere in your PATH:
-
-#! /bin/bash
-java -jar ~/antlrsrc/code/antlr/main/target/antlr-master-3.4-SNAPSHOT-completejar.jar $*
-
-Version Numbering
--------------------
-
-The first and Golden rule is that any pom files stored under the main
-branch of the toolset should never be modified to contain a release
-version number. They should always contain a.b.c-SNAPSHOT
-(e.g. 3.1.3-SNAPSHOT). Only release branches should have their pom
-version numbers set to a release version. You can release as many
-SNAPSHOTS as you like, but only one release version. However, release
-versions may be updated with a patch level: 3.1.3-1, 3.1.3-2 and so
-on.
-
-Fortunately, Maven helps us with the version numbering in a number of
-ways. Firstly, the pom.xml files for the various modules do not
-specify a version of the artifacts themselves. They pick up their
-version number from the master build pom.  However, there is a catch,
-because they need to know what version of the parent pom they inherit
-from and so they DO mention the version number. However, this does
-prevent accidentally releasing different versions of sub-modules than
-the master pom describes.
-
-Fortunately once again, Maven has a neat way of helping us change the
-version.  All you need do is check out all the pom.xml files from
-perforce, then modify the <version>a.b.c-SNAPSHOT</version> in the
-master pom. When the version number is correct in the master pom, you
-make sure your working directory is the location of the master pom and
-type:
-
-mvn versions:update-child-modules
-
-This command will then update the child pom.xml files to reflect the
-version number defined in the master pom.xml.
-
-There is unfortunately one last catch here though and that is that the
-antlr3-maven-plugin and the gunit-maven-plugin are not able to use the
-parent pom. The reason for this is subtle but makes sense as doing so
-would create a circular dependency between the ANTLR tool (which uses
-the plugin to build its own grammar files), and the plugins (which
-uses the tool to build grammar files and gunit to test).
-
-This catch-22 situation means that the pom.xml file in the
-antlr3-maven-plugin directory and the one in the gunit-maven-plugin
-directory MUST be updated manually (or we must write a script to do
-this).
-
-Finally, we need to remember that because the tool is dependent on the
-antlr3-maven-plugin and the plugin is itself dependent on the
-tool, that we must manually update the versions of each that they
-reference. So, when we bump the version of the toolset to say
-3.1.4-SNAPSHOT, we need to change the antlr3-maven-plugin pom.xml and
-the gunit-maven-plugin pom.xml to reference that version of the antlr
-tool. The tool itself is always built with the prior released version
-of the plugin, so when we release we must change the main branch of
-the plugin to use the newly released version of the plugin. This is
-covered in the release checklist.
-
-Deploying
-----------
-
-Deploying the tools at the current version is relatively easy, but to
-deploy to the ANTLR repositories (snapshot or release) you must have
-been granted access to the Sonatype OSS repositories' ANTLR login. 
-Few people will have this access of course.
-
-Next, because we do not publish access information for antlr.org, you
-will need to configure the repository server names locally. You do
-this by creating (or adding to) the file:
-
-~/.m2/settings.xml
-
-Which should look like this:
-
-<?xml version="1.0" encoding="UTF-8"?>
-<settings>
-  <servers>
-    <server>
-      <id>sonatype-nexus-snapshots</id>
-      <username>xxxxxxx</username>
-      <password>xxxxxxx</password>
-    </server>
-    <server>
-      <id>sonatype-nexus-staging</id>
-      <username>xxxxxxx</username>
-      <password>xxxxxxx</password>
-    </server>
-  </servers>
-</settings>
-
-When this configuration is in place, you will be able to deploy the components,
-either individually or from the master directory:
-
-mvn -Dmaven.test.skip=true -Ddeplot deploy
-
-You will then see lots of information about checking existing version
-information and so on, and the components will be deployed once you
-supply the ANTLR public key passphrase to sign the jars.
-
-Note that so long as the artifacts are versioned with a.b.c-SNAPSHOT
-then deployment will always be to the development snapshot
-directory. When the artifacts are versioned with a release version
-then deployment will be to the release stahinh repository, which
-will then be mirrored around the world if closed and release.
-The sonatype documentation should be consulted.
-
-Release Checklist
-------------------
-
-Here is the procedure to use to make a release of ANTLR. Note that we
-should really use the mvn release:release command, but the perforce
-plugin for Maven is not commercial quality and I want to rewrite it.
-
-For this checklist, let's assume that the current development version
-of ANTLR is 3.1.3-SNAPSHOT. This means that it will probably (but not
-necessarily) become release version 3.1.3 and that the development
-version will bump to 3.1.4-SNAPSHOT.
-
-0) Run a build of the main branch and check that it is builds and
-   passes as many tests as you want it to.
-
-1) First make a branch from main into the target release
-   directory. Then submit this to perforce. You could change versions
-   numbers before submitting, but doing that in separate stages will
-   keep things sane;
-
---- Use main development branch from here ---
-
-2) Before we deploy the release, we want to update the versions of the
-   development branch, so we don't deploy what is now the new release
-   as an older snapshot (this is not super important, but procedure is
-   good right?).
-
-   Check out all the pom.xml files (and if you are using any
-   antlr.config parameters that must change, then do that too).
-
-3) Edit the master pom.xml in the main directory and change the version from
-   3.1.3-SNAPSHOT to 3.1.4-SNAPSHOT.
-
-4) Edit the pom.xml file for antlr3-maven-plugin under the main
-   directory and change the version from 3.1.3-SNAPSHOT to
-   3.1.4-SNAPSHOT. Do the same for the pom.xml in the
-   gunit-maven-plugin directory.
-
-   Update the pom.xml for the archetype manually too.
-
-5) Now (from the main directory), run the command:
-
-         mvn versions:update-child-modules
-
-      You should see:
-
-         [INFO] [versions:update-child-modules]
-         [INFO] Module: gunit
-         [INFO]   Parent is org.antlr:antlr-master:3.1.4-SNAPSHOT
-         [INFO] Module: runtime/Java
-         [INFO]   Parent is org.antlr:antlr-master:3.1.4-SNAPSHOT
-         [INFO] Module: tool
-         [INFO]   Parent is org.antlr:antlr-master:3.1.4-SNAPSHOT
-
-6) Run a build of the main branch:
-
-         mvn -Dmaven.test.skip=true
-
-       All should be good.
-
-7) Submit the pom changes of the main branch to perforce.
-
-8) Deploy the new snapshot as a placeholder for the next release. It
-   will go to the snapshot repository of course:
-
-	  mvn -N deploy
-          mvn -Dmaven.test.skip=true deploy
-
-9) You are now finished with the main development branch and should change
-   working directories to the release branch you made earlier.
-
---- Use release branch from here ---
-
-10) Check out all the pom.xml files in the release branch (and if you are
-    using any antlr.config parameters that must change, then do that too).
-
-11) Edit the master pom.xml in the release-3.1.3 directory and change
-    the version from 3.1.3-SNAPSHOT to 3.1.3.
-
-12) Edit the pom.xml file for antlr3-maven-plugin under the
-    release-3.1.3 directory and change the version from 3.1.3-SNAPSHOT
-    to 3.1.3. Also change the version of the tool that the this
-    pom.xml references from 3.1.3-SNAPSHOT to 3.1.3 as we are now
-    releasing the plugin of course and it needs to reference the
-    version we are about to release. You will find this reference in
-    the dependencies section of the antlr3-maven-plugin pom.xml. Also
-    change the version references in the pom for gunit-maven-plugin.
-
-13)  Now (from the release-3.1.3 directory), run the command:
-
-           mvn versions:update-child-modules
-
-        You should see:
-
-	[INFO] [versions:update-child-modules]
-	[INFO] Module: gunit
-	[INFO]   Parent was org.antlr:antlr-master:3.1.3-SNAPSHOT,
-	       now org.antlr:antlr-master:3.1.3
-	[INFO] Module: runtime/Java
-	[INFO]   Parent was org.antlr:antlr-master:3.1.3-SNAPSHOT,
-	       now org.antlr:antlr-master:3.1.3
-	[INFO] Module: tool
-	[INFO]   Parent was org.antlr:antlr-master:3.1.3-SNAPSHOT,
-	       now org.antlr:antlr-master:3.1.3
-
-14)  Run a build of the release-3.1.3 branch:
-
-           mvn   # Note I am letting unit tests run here!
-
-        All should be good, or as good as it gets ;-)
-
-15)  Submit the pom changes of the release-3.1.3 branch to perforce.
-
-16)  Deploy the new release (this is it guys, make sure you are happy):
-
-	  mvn -N deploy
-          mvn -Dmaven.test.skip=true deploy
-
-        Note that we must skip the tests as Maven will not let you
-        deploy releases that fail any junit tests.
-
-17) The final step is that we must update the main branch pom.xml for
-     the tool to reference the newly release version of the
-     antlr3-maven-plugin. This is because each release of ANTLR is
-     built with the prior release of ANTLR, and we have just released
-     a new version. Edit the pom.xml for the tool (main/tool/pom.xml)
-     under the main (that's the MAIN branch, not the release branch)
-     and find the dependency reference to the antlr plugin. If you
-     just released say 3.1.3, then the tool should now reference
-     version 3.1.3 of the plugin. Having done this, you should
-     probably rebuild the main branch and let it run the junit
-     tests. Later, I will automate this dependency update as mvn can
-     do this for us.
-
-18)  Having deployed the release to maven, you will want to create the
-     uber jar for the new release, to make it downloadable from the
-     antlr.org website. This is a repeat of the earlier described step
-     to build the uber jar:
-
-       mvn -Dmaven.test.skip=true package assembly:assembly
-
-     MAven will produce the uber jar in the target directory:
-
-	antlr-master-3.1.3-completejar.jar
-
-     And this is the complete jar that can be downloaded from the web site. You
-     may wish to produce an md5 checksum to go with the jar:
-
-     md5sum target/antlr-master-3.1.3-completejar.jar
-     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  target/antlr-master-3.1.4-SNAPSHOT-completejar.jar
-
-     The command you just ran will also produce a second jar:
-
-        antlr-master-3.1.3-src.jar
-
-     This is the source code for everythign you just deployed and can
-     be unjarred and built from scratch using the very procedures
-     described here, which means you will now be reading this
-     BUILD.txt file for ever.
-
-19)  Reward anyone around you with good beer.
-
-
-Miscellany
------------
-
-It was a little tricky to get all the interdependencies correct
-because ANTLR builds itself using itself and the maven plugin
-references the ANTLR Tool as well. Hence the maven tool is not a child
-project of the master pom.xml file, even though it is built by it.
-
-An observant person will not that when the assembly:assembly phase is
-run, that it invokes the build of the ANTLR tool using the version of
-the Maven plugin that it has just built, and this results in the
-plugin using the version of ANTLR tool that it has just built. This is
-safe because everything will already be up to date and so we package
-up the version of the tool that we expect, but the Maven plugin we
-deploy will use the correct version of ANTLR, even though there is
-technically a circular dependency.
-
-The master pom.xml does give us a way to cause the build of the ANTLR
-tool to use itself to build itself. This is because in
-dependencyManagement in the master pom.xml, we can reference the
-current version of the Tool and the Maven plugin, even though in the
-pom.xml for the tool itself refers to the previous version of the
-plugin.
-
-What happens is that if we first cd into the tool and maven
-directories and build ANTLR, it will build itself with the prior
-version and this will deploy locally (.m2). We can then clean build
-from the master pom and when ANTLR asks for the prior version of the
-tool, the master pom.xml will override it and build with the interim
-versions we just built manually.
-
-However, strictly speaking, we need a third build where we rebuild the
-tool again with the version of the tool that was built with itself and
-not deploy the version that was built by the version of itself that
-was built by a prior version of itself. I decided that this was not
-particularly useful and complicates things too much. Building with a
-prior version of the tool is fine and if there was ever a need to, we
-could release twice in quick succession.
-
-I have occasionally seen the MAven reactor screw up (or perhaps it is
-the ANTLR tool) when building. If this happens you will see an ANTLR
-Panic - cannot find en.stg message. If this happens to you, then just
-rerun the build and it will eventually work.
-
-Jim Idle - March 2009
-
+The notes are by Jim Idle (and are a bit out of date but we hope to
+update them).
diff --git a/METADATA b/METADATA
index 377e0f8..a19780f 100644
--- a/METADATA
+++ b/METADATA
@@ -1,7 +1,5 @@
 name: "antlr3"
-description:
-    "ANTLR (ANother Tool for Language Recognition) is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages."
-
+description: "ANTLR (ANother Tool for Language Recognition) is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages."
 third_party {
   url {
     type: HOMEPAGE
@@ -9,8 +7,12 @@
   }
   url {
     type: ARCHIVE
-    value: "https://github.com/antlr/antlr3/archive/antlr-3.4.zip"
+    value: "https://github.com/antlr/antlr3/archive/3.5.2.zip"
   }
-  version: "3.4"
-  last_upgrade_date { year: 2011 month: 11 day: 15 }
+  version: "3.5.2"
+  last_upgrade_date {
+    year: 2018
+    month: 8
+    day: 28
+  }
 }
diff --git a/README.txt b/README.txt
new file mode 100644
index 0000000..c2fa6c4
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,142 @@
+ANTLR v3.5
+January 4, 2013
+
+Terence Parr, parrt at cs usfca edu
+ANTLR project lead and supreme dictator for life
+University of San Francisco
+
+INTRODUCTION
+
+Welcome to ANTLR v3!  ANTLR (ANother Tool for Language Recognition) is
+a language tool that provides a framework for constructing
+recognizers, interpreters, compilers, and translators from grammatical
+descriptions containing actions in a variety of target
+languages. ANTLR provides excellent support for tree construction,
+tree walking, translation, error recovery, and error reporting. I've
+been working on parser generators for 25 years and on this particular
+version of ANTLR for 9 years.
+
+You should use v3 in conjunction with ANTLRWorks:
+
+    http://www.antlr.org/works/index.html
+
+and gUnit (grammar unit testing tool included in distribution):
+
+    http://www.antlr.org/wiki/display/ANTLR3/gUnit+-+Grammar+Unit+Testing
+
+The book will also help you a great deal (printed May 15, 2007); you
+can also buy the PDF:
+
+    http://www.pragmaticprogrammer.com/titles/tpantlr/index.html
+
+2nd book, Language Implementation Patterns:
+
+    http://pragprog.com/titles/tpdsl/language-implementation-patterns
+
+See the getting started document:
+
+    http://www.antlr.org/wiki/display/ANTLR3/FAQ+-+Getting+Started
+
+You also have the examples plus the source to guide you.
+
+See the wiki FAQ:
+
+    http://www.antlr.org/wiki/display/ANTLR3/ANTLR+v3+FAQ
+
+and general doc root:
+
+    http://www.antlr.org/wiki/display/ANTLR3/ANTLR+3+Wiki+Home
+
+Please help add/update FAQ entries.
+
+If all else fails, you can buy support or ask the antlr-interest list:
+
+    http://www.antlr.org/support.html
+
+Per the license in LICENSE.txt, this software is not guaranteed to
+work and might even destroy all life on this planet:
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+
+EXAMPLES
+
+ANTLR v3 sample grammars:
+
+    https://github.com/antlr/examples-v3
+
+Examples from Language Implementation Patterns:
+
+    http://www.pragprog.com/titles/tpdsl/source_code
+
+----------------------------------------------------------------------
+
+What is ANTLR?
+
+ANTLR stands for (AN)other (T)ool for (L)anguage (R)ecognition
+and generates LL(*) recursive-descent parsers. ANTLR is a language tool
+that provides a framework for constructing recognizers, compilers, and
+translators from grammatical descriptions containing actions.
+Target language list:
+
+http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets
+
+----------------------------------------------------------------------
+
+How is ANTLR v3 different than ANTLR v2?
+
+See "What is the difference between ANTLR v2 and v3?"
+
+    http://www.antlr.org/wiki/pages/viewpage.action?pageId=719
+
+See migration guide:
+
+    http://www.antlr.org/wiki/display/ANTLR3/Migrating+from+ANTLR+2+to+ANTLR+3
+
+----------------------------------------------------------------------
+
+How do I install this damn thing?
+
+You will have grabbed either of these:
+
+	http://antlr.org/download/antlr-3.5-complete-no-st3.jar
+	http://antlr.org/download/antlr-3.5-complete.jar
+
+It has all of the jars you need combined into one. Then you need to
+add antlr-3.5-complete.jar to your CLASSPATH or add to arg list; e.g., on unix:
+
+$ java -cp "/usr/local/lib/antlr-3.5-complete.jar:$CLASSPATH" org.antlr.Tool Test.g
+
+Source + java binaries: Just untar antlr-3.5.tar.gz and you'll get:
+
+antlr-3.5/BUILD.txt
+antlr-3.5/antlr3-maven-plugin
+antlr-3.5/antlrjar.xml
+antlr-3.5/antlrsources.xml
+antlr-3.5/gunit
+antlr-3.5/gunit-maven-plugin
+antlr-3.5/pom.xml
+antlr-3.5/runtime
+antlr-3.5/tool
+antlr-3.5/lib
+
+Please see the FAQ
+
+    http://www.antlr.org/wiki/display/ANTLR3/ANTLR+v3+FAQ
+
+-------------------------
+
+How can I contribute to ANTLR v3?
+
+http://www.antlr.org/wiki/pages/viewpage.action?pageId=33947666
diff --git a/README.version b/README.version
deleted file mode 100644
index 7270f7b..0000000
--- a/README.version
+++ /dev/null
@@ -1,3 +0,0 @@
-URL: https://github.com/antlr/website-antlr3/raw/gh-pages/download/antlr-3.4.tar.gz
-Version: 3.4
-BugComponent: 99142
diff --git a/antlr-complete/antlr.config b/antlr-complete/antlr.config
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/antlr-complete/antlr.config
diff --git a/antlr-complete/pom.xml b/antlr-complete/pom.xml
new file mode 100644
index 0000000..aad3c68
--- /dev/null
+++ b/antlr-complete/pom.xml
@@ -0,0 +1,137 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>antlr-complete</artifactId>
+    <packaging>jar</packaging>
+
+    <name>ANTLR 3 Complete</name>
+    <description>Complete distribution for ANTLR 3</description>
+
+  <!--
+
+    Inherit from the ANTLR master pom, which tells us what
+    version we are and allows us to inherit dependencies
+    and so on.
+
+    -->
+    <parent>
+        <groupId>org.antlr</groupId>
+        <artifactId>antlr-master</artifactId>
+        <version>3.5.2</version>
+    </parent>
+
+    <url>http://antlr.org/</url>
+
+    <!--
+        The complete distribution includes the following modules and their dependencies:
+            ANTLR 3 Tool
+            ANTLR 3 Runtime
+            gUnit for ANTLR 3
+            StringTemplate 4 (dependency of code generator in the ANTLR 3 Tool)
+            StringTemplate 3 (dependency of grammars with output=template)
+            ANTLR 2.7.7 (dependency of template parser in StringTemplate 3)
+    -->
+    <dependencies>
+
+        <dependency>
+            <groupId>org.antlr</groupId>
+            <artifactId>antlr</artifactId>
+            <version>${project.version}</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.antlr</groupId>
+            <artifactId>antlr-runtime</artifactId>
+            <version>${project.version}</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.antlr</groupId>
+            <artifactId>gunit</artifactId>
+            <version>${project.version}</version>
+            <scope>compile</scope>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+
+        <plugins>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>2.0</version>
+                <configuration>
+                    <minimizeJar>false</minimizeJar>
+                    <createSourcesJar>true</createSourcesJar>
+                    <filters>
+                        <filter>
+                            <artifact>org.antlr:antlr-complete</artifact>
+                            <includes>
+                                <include>META-INF/**</include>
+                            </includes>
+                        </filter>
+                    </filters>
+                    <transformers>
+                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+                            <mainClass>org.antlr.Tool</mainClass>
+                        </transformer>
+                    </transformers>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>complete-no-st3</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <createDependencyReducedPom>false</createDependencyReducedPom>
+                            <shadedArtifactAttached>true</shadedArtifactAttached>
+                            <shadedClassifierName>no-st3</shadedClassifierName>
+                            <filters>
+                                <filter>
+                                    <artifact>antlr:antlr</artifact>
+                                    <excludes>
+                                        <exclude>**</exclude>
+                                    </excludes>
+                                </filter>
+                                <filter>
+                                    <artifact>org.antlr:stringtemplate</artifact>
+                                    <excludes>
+                                        <exclude>**</exclude>
+                                    </excludes>
+                                </filter>
+                            </filters>
+                        </configuration>
+                    </execution>
+
+                    <execution>
+                        <id>complete</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <createDependencyReducedPom>false</createDependencyReducedPom>
+                            <shadedArtifactAttached>false</shadedArtifactAttached>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <configuration>
+                    <includeDependencySources>true</includeDependencySources>
+                </configuration>
+            </plugin>
+        </plugins>
+
+    </build>
+
+</project>
diff --git a/antlr.config b/antlr.config
index 00ac54e..e69de29 100644
--- a/antlr.config
+++ b/antlr.config
@@ -1 +0,0 @@
-fred=99
diff --git a/antlr3-maven-archetype/pom.xml b/antlr3-maven-archetype/pom.xml
index 6de349c..c4b084b 100644
--- a/antlr3-maven-archetype/pom.xml
+++ b/antlr3-maven-archetype/pom.xml
@@ -1,82 +1,27 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 
     
     <modelVersion>4.0.0</modelVersion>
     <groupId>org.antlr</groupId>
     <artifactId>antlr3-maven-archetype</artifactId>
-    <version>3.4</version>
     <packaging>maven-archetype</packaging>
-    <name>ANTLR3 Maven Archetype 3.4</name>
+    <name>ANTLR 3 Maven Archetype</name>
+    <description>ANTLR 3 Maven Archetype</description>
     
-    <properties>
-        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-    </properties>
-    
+
     <!--
 
     Inherit from the ANTLR master pom, which tells us what
     version we are and allows us to inherit dependencies
     and so on.
-
-    Unfortunately, because of a bug in the archetype plugin
-    we cannot use the parent pom because it causes the
-    artifactId in the generated pom to be set to antlr3-maven-archetype
-    We will reinstate this parent usage when that is fixed.
-    
+    -->
     <parent>
         <groupId>org.antlr</groupId>
         <artifactId>antlr-master</artifactId>
-        <version>3.4</version>
+        <version>3.5.2</version>
     </parent>
-    -->
-    <!--
-        The ANTLR Maven artifacts are now released via the Sonotype OSS
-        repository, which means that they are synced to Maven central 
-        within a few minutes of hitting the release repo for Sonotype.
-        To enable this, we inherit from the Sonotype provided parent
-        pom. However, we must also configure our .m2/settings.xml to include
-        the snapshot and staging server and the sonotype password. This 
-        means that only ANTLR developers can released the artifacts, but
-        anyone can build locally.
-      -->
-    <parent>
-        <groupId>org.sonatype.oss</groupId>
-        <artifactId>oss-parent</artifactId>
-        <version>7</version>
-    </parent> 
-    
-    <profiles>
-        <profile>
-            <id>release-sign-artifacts</id>
-            <activation>
-                <property>
-                    <name>deploy</name>
-                    <value>true</value>
-                </property>
-            </activation>
-            <build>
-                <plugins>
-                    <plugin>
-                        <groupId>org.apache.maven.plugins</groupId>
-                        <artifactId>maven-gpg-plugin</artifactId>
-                        <version>1.3</version>
-                        <executions>
-                            <execution>
-                                <id>sign-artifacts</id>
-                                <phase>verify</phase>
-                                <goals>
-                                   <goal>sign</goal>
-                                </goals>
-                            </execution>
-                        </executions>
-                    </plugin>
-                </plugins>
-            </build>
-        </profile>
-    </profiles>
-    
+
   <build>
 
     <extensions>
@@ -84,7 +29,7 @@
       <extension>
         <groupId>org.apache.maven.archetype</groupId>
         <artifactId>archetype-packaging</artifactId>
-        <version>2.0</version>
+        <version>2.2</version>
       </extension>
 
     </extensions>
@@ -93,38 +38,10 @@
 
             <plugin>
                 <artifactId>maven-archetype-plugin</artifactId>
-                <version>2.0</version>
+                <version>2.2</version>
                 <extensions>true</extensions>
             </plugin>
 
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-source-plugin</artifactId>
-                <version>2.1.2</version>
-                <executions>
-                    <execution>
-                        <id>attach-sources</id>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-			
-            <plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-javadoc-plugin</artifactId>
-                <version>2.8</version>
-				<executions>
-					<execution>
-						<id>attach-javadocs</id>
-						<goals>
-							<goal>jar</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-            
         </plugins>
 
   </build>
diff --git a/antlr3-maven-archetype/src/main/resources/archetype-resources/pom.xml b/antlr3-maven-archetype/src/main/resources/archetype-resources/pom.xml
index e8db114..d0509c9 100644
--- a/antlr3-maven-archetype/src/main/resources/archetype-resources/pom.xml
+++ b/antlr3-maven-archetype/src/main/resources/archetype-resources/pom.xml
@@ -24,7 +24,7 @@
          Archetype by Jim Idle (jimi@temporal-wave.com) - Oct 2009
          Report bugs to the ANTLR interest list at http://www.antlr.org
 
-         Generated by antlr3-maven-archetype version 3.4
+         Generated by antlr3-maven-archetype version 3.4.1-SNAPSHOT
          =======================================================================
       -->
 
@@ -58,7 +58,7 @@
         <dependency>
             <groupId>org.antlr</groupId>
             <artifactId>antlr-runtime</artifactId>
-            <version>3.4</version>
+            <version>3.4.1-SNAPSHOT</version>
             <scope>compile</scope>
         </dependency>
 
@@ -84,7 +84,7 @@
 
                 <groupId>org.antlr</groupId>
                 <artifactId>antlr3-maven-plugin</artifactId>
-                <version>3.4</version>
+                <version>3.4.1-SNAPSHOT</version>
                 <executions>
                     <execution>
                         <goals>
@@ -100,7 +100,7 @@
               the prototype, but we use it to illustrate how you can get
               the JDK 6 Java compiler to accept 1.5 or 1.6 targeted source code
               but produce class files that are compatible with JRE 1.4. As
-              Michael Caine might not say, "Not a lot of people know that!"
+              Michael Caine might say, "Not a lot of people know that!"
               -->
             <plugin>
                 <artifactId>maven-compiler-plugin</artifactId>
diff --git a/antlr3-maven-plugin/antlr.config b/antlr3-maven-plugin/antlr.config
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/antlr3-maven-plugin/antlr.config
diff --git a/antlr3-maven-plugin/pom.xml b/antlr3-maven-plugin/pom.xml
index 58dc982..6fc1770 100644
--- a/antlr3-maven-plugin/pom.xml
+++ b/antlr3-maven-plugin/pom.xml
@@ -33,26 +33,8 @@
 
 
 
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
-
-    <!--
-        The ANTLR Maven artifacts are now released via the Sonotype OSS
-        repository, which means that they are synced to Maven central 
-        within a few minutes of hitting the release repo for Sonotype.
-        To enable this, we inherit from the Sonotype provided parent
-        pom. However, we must also configure our .m2/settings.xml to include
-        the snapshot and staging server and the sonotype password. This 
-        means that only ANTLR developers can released the artifacts, but
-        anyone can build locally.
-      -->
-    <parent>
-        <groupId>org.sonatype.oss</groupId>
-        <artifactId>oss-parent</artifactId>
-        <version>7</version>
-    </parent>  
-    
     <!-- Maven model we are inheriting from
       -->
     <modelVersion>4.0.0</modelVersion>
@@ -77,12 +59,13 @@
     <artifactId>antlr3-maven-plugin</artifactId>
     <packaging>maven-plugin</packaging>
 
-    <!-- Note that as this plugin depends on the ANTLR tool itself
-         we cannot use the paren pom to control the version number
-         and MUST update <version> in this pom manually!
-         -->
-    <version>3.4</version>
-    <name>Maven plugin for ANTLR V3.4</name>
+    <parent>
+        <groupId>org.antlr</groupId>
+        <artifactId>antlr-master</artifactId>
+        <version>3.5.2</version>
+    </parent>
+
+    <name>ANTLR 3 Maven plugin</name>
     <prerequisites>
         <maven>2.0</maven>
     </prerequisites>
@@ -126,44 +109,13 @@
 
     </description>
 
-    <profiles>
-        <profile>
-            <id>release-sign-artifacts</id>
-            <activation>
-                <property>
-                    <name>deploy</name>
-                    <value>true</value>
-                </property>
-            </activation>
-            <build>
-                <plugins>
-                    <plugin>
-                        <groupId>org.apache.maven.plugins</groupId>
-                        <artifactId>maven-gpg-plugin</artifactId>
-                        <version>1.3</version>
-                        <executions>
-                            <execution>
-                                <id>sign-artifacts</id>
-                                <phase>verify</phase>
-                                <goals>
-                                   <goal>sign</goal>
-                                </goals>
-                            </execution>
-                        </executions>
-                    </plugin>
-                </plugins>
-            </build>
-        </profile>
-    </profiles>
-
-
     <developers>
 
         <developer>
             <name>Jim Idle</name>
             <url>http://www.temporal-wave.com</url>
             <roles>
-                <role>Originator, version 3.1.3+</role>
+                <role>Originator, version 3.1.3</role>
             </roles>
         </developer>
 
@@ -193,44 +145,6 @@
 
     </developers>
 
-    <!-- Where do we track bugs for this project?
-      -->
-    <issueManagement>
-        <system>JIRA</system>
-        <url>http://antlr.org/jira/browse/ANTLR</url>
-    </issueManagement>
-
-    <!-- Location of the license description for this project
-      -->
-    <licenses>
-        <license>
-            <distribution>repo</distribution>
-            <name>The BSD License</name>
-            <url>http://www.antlr.org/LICENSE.txt </url>
-        </license>
-    </licenses>
-    
-    <!-- Ancilliary information for completeness
-      -->
-    <inceptionYear>2009</inceptionYear>
-
-    <mailingLists>
-        <mailingList>
-            <archive>http://antlr.markmail.org/</archive>
-            <otherArchives>
-                <otherArchive>http://www.antlr.org/pipermail/antlr-interest/</otherArchive>
-            </otherArchives>
-            <name>ANTLR Users</name>
-            <subscribe>http://www.antlr.org/mailman/listinfo/antlr-interest/</subscribe>
-            <unsubscribe>http://www.antlr.org/mailman/options/antlr-interest/</unsubscribe>
-            <post>antlr-interest@antlr.org</post>
-        </mailingList>
-    </mailingLists>
-
-    <organization>
-        <name>ANTLR.org</name>
-        <url>http://www.antlr.org</url>
-    </organization>
     <!-- ============================================================================= -->
 
     <!--
@@ -261,7 +175,7 @@
         <dependency>
             <groupId>org.codehaus.plexus</groupId>
             <artifactId>plexus-compiler-api</artifactId>
-            <version>1.5.3</version>
+            <version>2.0</version>
         </dependency>
 
         <!--
@@ -272,25 +186,13 @@
         <dependency>
             <groupId>org.antlr</groupId>
             <artifactId>antlr</artifactId>
-            <version>3.4</version>
-        </dependency>
-
-        <!--
-          Testing requirements...
-          -->
-        <dependency>
-
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <version>4.8.2</version>
-            <scope>test</scope>
-
+            <version>${project.version}</version>
         </dependency>
 
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-plugin-testing-harness</artifactId>
-            <version>1.0</version>
+            <version>1.1</version>
             <scope>test</scope>
         </dependency>
         
@@ -298,64 +200,34 @@
     
     <build>
 
-        <defaultGoal>install</defaultGoal>
-
         <plugins>
 
             <plugin>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <version>2.0.2</version>
-                <configuration>
-                    <source>1.6</source>
-                    <target>jsr14</target>
-                </configuration>
-            </plugin>
-
-            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-site-plugin</artifactId>
-                <version>2.0</version>
+                <version>3.3</version>
             </plugin>
 
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-project-info-reports-plugin</artifactId>
-                <version>2.1.1</version>
+                <version>2.7</version>
                 <configuration>
                     <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
                 </configuration>
             </plugin>
 
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-source-plugin</artifactId>
-                <version>2.1.2</version>
-                <executions>
-                    <execution>
-                        <id>attach-sources</id>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-javadoc-plugin</artifactId>
-                <version>2.8</version>
-				<executions>
-					<execution>
-						<id>attach-javadocs</id>
-						<goals>
-							<goal>jar</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-            
         </plugins>
 
     </build>
 
+    <reporting>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-plugin-plugin</artifactId>
+                <version>3.2</version>
+            </plugin>
+        </plugins>
+    </reporting>
 </project>
diff --git a/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3ErrorLog.java b/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3ErrorLog.java
index bf2c3c6..5a315da 100644
--- a/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3ErrorLog.java
+++ b/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3ErrorLog.java
@@ -56,7 +56,7 @@
 
     /**
      * Sends an informational message to the Maven log sink.
-     * @param s The message to send to Maven
+     * @param message The message to send to Maven
      */
     public void info(String message) {
         log.info(message);
diff --git a/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3Mojo.java b/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3Mojo.java
index e7225d3..6c18c55 100644
--- a/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3Mojo.java
+++ b/antlr3-maven-plugin/src/main/java/org/antlr/mojo/antlr3/Antlr3Mojo.java
@@ -45,7 +45,6 @@
 import java.util.HashSet;
 import java.util.Set;
 import org.antlr.Tool;
-import org.antlr.runtime.RecognitionException;
 import org.apache.maven.plugin.logging.Log;
 import org.codehaus.plexus.compiler.util.scan.InclusionScanException;
 import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner;
@@ -54,13 +53,11 @@
 import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;
 
 /**
- * Goal that picks up all the ANTLR grammars in a project and moves those that
- * are required for generation of the compilable sources into the location
- * that we use to compile them, such as target/generated-sources/antlr3 ...
+ * Parses ANTLR grammar files {@code *.g} and transforms them into Java source
+ * files.
  *
  * @goal antlr
- * 
- * @phase process-sources
+ * @phase generate-sources
  * @requiresDependencyResolution compile
  * @requiresProject true
  * 
@@ -82,7 +79,7 @@
     protected boolean report;
     /**
      * If set to true, then the ANTLR tool will print a version of the input
-     * grammar which is devoid of any actions that may be present in the input file.
+     * grammar(s) which are stripped of any embedded actions.
      *
      * @parameter default-value="false"
      */
@@ -96,119 +93,124 @@
      */
     protected boolean debug;
     /**
-     * If set to true, then then the generated parser will compute and report on
-     * profile information at runtime.
+     * If set to true, then the generated parser will compute and report profile
+     * information at runtime.
      *
      * @parameter default-value="false"
      */
     protected boolean profile;
     /**
-     * If set to true then the ANTLR tool will generate a description of the nfa
-     * for each rule in <a href="http://www.graphviz.org">Dot format</a>
-     * 
+     * If set to true, then the ANTLR tool will generate a description of the
+     * NFA for each rule in <a href="http://www.graphviz.org">Dot format</a>
+     *
      * @parameter default-value="false"
      */
     protected boolean nfa;
     /**
-     * If set to true then the ANTLR tool will generate a description of the DFA
-     * for each decision in the grammar in <a href="http://www.graphviz.org">Dot format</a>
-     * 
+     * If set to true, then the ANTLR tool will generate a description of the
+     * DFA for each decision in the grammar in
+     * <a href="http://www.graphviz.org">Dot format</a>.
+     *
      * @parameter default-value="false"
      */
     protected boolean dfa;
     /**
-     * If set to true, the generated parser code will log rule entry and exit points
-     * to stdout as an aid to debugging.
+     * If set to true, the generated parser code will log rule entry and exit
+     * points to stdout ({@link System#out} for the Java target) as an aid to
+     * debugging.
      *
      * @parameter default-value="false"
      */
     protected boolean trace;
     /**
-     * If this parameter is set, it indicates that any warning or error messages returned
-     * by ANLTR, should be formatted in the specified way. Currently, ANTLR supports the
-     * built-in formats of antlr, gnu and vs2005.
+     * If this parameter is set, it indicates that any warning or error messages
+     * returned by ANLTR, should be formatted in the specified way. Currently,
+     * ANTLR supports the built-in formats {@code antlr}, {@code gnu} and
+     * {@code vs2005}.
      *
      * @parameter default-value="antlr"
      */
     protected String messageFormat;
     /**
-     * If this parameter is set to true, then ANTLR will report all sorts of things
-     * about what it is doing such as the names of files and the version of ANTLR and so on.
+     * If set to true, then ANTLR will report verbose messages during the code
+     * generation process. This includes the names of files, the version of
+     * ANTLR, and more.
      *
      * @parameter default-value="true"
      */
     protected boolean verbose;
 
     /**
-     * The number of alts, beyond which ANTLR will not generate a switch statement
-     * for the DFA.
+     * The maximum number of alternatives allowed in an inline switch statement.
+     * Beyond this, ANTLR will not generate a switch statement for the DFA.
      *
      * @parameter default-value="300"
      */
     private int maxSwitchCaseLabels;
 
     /**
-     * The number of alts, below which ANTLR will not choose to generate a switch
-     * statement over an if statement.
+     * The minimum number of alternatives for ANTLR to generate a switch
+     * statement. For decisions with fewer alternatives, an if/else if/else
+     * statement will be used instead.
+     *
+     * @parameter default-value="3"
      */
     private int minSwitchAlts;
 
     /* --------------------------------------------------------------------
-     * The following are Maven specific parameters, rather than specificlly
+     * The following are Maven specific parameters, rather than specific
      * options that the ANTLR tool can use.
      */
+
     /**
-     * Provides an explicit list of all the grammars that should
-     * be included in the generate phase of the plugin. Note that the plugin
-     * is smart enough to realize that imported grammars should be included but
-     * not acted upon directly by the ANTLR Tool.
-     *
-     * Unless otherwise specified, the include list scans for and includes all
-     * files that end in ".g" in any directory beneath src/main/antlr3. Note that
-     * this version of the plugin looks for the directory antlr3 and not the directory
-     * antlr, so as to avoid clashes and confusion for projects that use both v2 and v3 grammars
-     * such as ANTLR itself.
+     * Provides an explicit list of all the grammars that should be included in
+     * the generate phase of the plugin. Note that the plugin is smart enough to
+     * realize that imported grammars should be included but not acted upon
+     * directly by the ANTLR Tool.
+     * <p>
+     * A set of Ant-like inclusion patterns used to select files from the source
+     * directory for processing. By default, the pattern <code>**&#47;*.g</code>
+     * is used to select grammar files.</p>
      *
      * @parameter
      */
-    protected Set includes = new HashSet();
+    protected Set<String> includes = new HashSet<String>();
     /**
-     * Provides an explicit list of any grammars that should be excluded from
-     * the generate phase of the plugin. Files listed here will not be sent for
-     * processing by the ANTLR tool.
+     * A set of Ant-like exclusion patterns used to prevent certain files from
+     * being processed. By default, this set is empty such that no files are
+     * excluded.
      *
-     * @parameter 
+     * @parameter
      */
-    protected Set excludes = new HashSet();
+    protected Set<String> excludes = new HashSet<String>();
     /**
+     * The current Maven project.
+     *
      * @parameter expression="${project}"
      * @required
      * @readonly
      */
     protected MavenProject project;
     /**
-     * Specifies the Antlr directory containing grammar files. For
-     * antlr version 3.x we default this to a directory in the tree
-     * called antlr3 because the antlr directory is occupied by version
-     * 2.x grammars.
+     * The directory where the ANTLR grammar files ({@code *.g}) are located.
      *
      * @parameter default-value="${basedir}/src/main/antlr3"
-     * @required
      */
     private File sourceDirectory;
     /**
-     * Location for generated Java files. For antlr version 3.x we default
-     * this to a directory in the tree called antlr3 because the antlr
-     * directory is occupied by version 2.x grammars.
+     * The directory where the parser files generated by ANTLR will be stored.
+     * The directory will be registered as a compile source root of the project
+     * such that the generated files will participate in later build phases like
+     * compiling and packaging.
      *
      * @parameter default-value="${project.build.directory}/generated-sources/antlr3"
      * @required
      */
     private File outputDirectory;
     /**
-     * Location for imported token files, e.g. <code>.tokens</code> and imported grammars.
-     * Note that ANTLR will not try to process grammars that it finds to be imported
-     * into other grammars (in the same processing session).
+     * Location for imported token files, e.g. {@code *.tokens} and imported
+     * grammars. Note that ANTLR will not try to process grammars that it finds
+     * to be imported into other grammars (in the same processing session).
      *
      * @parameter default-value="${basedir}/src/main/antlr3/imports"
      */
@@ -230,16 +232,18 @@
         project.addCompileSourceRoot(outputDir.getPath());
     }
     /**
-     * An instance of the ANTLR tool build
+     * An instance of the ANTLR tool build.
      */
     protected Tool tool;
 
     /**
      * The main entry point for this Mojo, it is responsible for converting
      * ANTLR 3.x grammars into the target language specified by the grammar.
-     * 
-     * @throws org.apache.maven.plugin.MojoExecutionException When something is discovered such as a missing source
-     * @throws org.apache.maven.plugin.MojoFailureException When something really bad happens such as not being able to create the ANTLR Tool
+     *
+     * @throws MojoExecutionException if a configuration or grammar error causes
+     * the code generation process to fail
+     * @throws MojoFailureException if an instance of the ANTLR 3 {@link Tool}
+     * cannot be created
      */
     public void execute()
             throws MojoExecutionException, MojoFailureException {
@@ -253,15 +257,13 @@
 
             // Excludes
             //
-            for (String e : (Set<String>) excludes) {
-
+            for (String e : excludes) {
                 log.debug("ANTLR: Exclude: " + e);
             }
 
             // Includes
             //
-            for (String e : (Set<String>) includes) {
-
+            for (String e : includes) {
                 log.debug("ANTLR: Include: " + e);
             }
 
@@ -401,20 +403,18 @@
      *
      * @param sourceDirectory
      * @param outputDirectory
-     * @throws antlr.TokenStreamException
-     * @throws antlr.RecognitionException
-     * @throws java.io.IOException
-     * @throws org.codehaus.plexus.compiler.util.scan.InclusionScanException
+     * @throws IOException
+     * @throws InclusionScanException
      */
     private void processGrammarFiles(File sourceDirectory, File outputDirectory)
-            throws RecognitionException, IOException, InclusionScanException {
+            throws IOException, InclusionScanException {
         // Which files under the source set should we be looking for as grammar files
         //
-        SourceMapping mapping = new SuffixMapping("g", Collections.EMPTY_SET);
+        SourceMapping mapping = new SuffixMapping("g", Collections.<String>emptySet());
 
         // What are the sets of includes (defaulted or otherwise).
         //
-        Set includes = getIncludesPatterns();
+        Set<String> includes = getIncludesPatterns();
 
         // Now, to the excludes, we need to add the imports directory
         // as this is autoscanned for importd grammars and so is auto-excluded from the
@@ -425,7 +425,7 @@
         SourceInclusionScanner scan = new SimpleSourceInclusionScanner(includes, excludes);
 
         scan.addSourceMapping(mapping);
-        Set grammarFiles = scan.getIncludedSources(sourceDirectory, null);
+        Set<File> grammarFiles = scan.getIncludedSources(sourceDirectory, null);
 
         if (grammarFiles.isEmpty()) {
             if (getLog().isInfoEnabled()) {
@@ -440,7 +440,7 @@
             // Iterate each grammar file we were given and add it into the tool's list of
             // grammars to process.
             //
-            for (File grammar : (Set<File>) grammarFiles) {
+            for (File grammar : grammarFiles) {
 
                 if (getLog().isDebugEnabled()) {
                     getLog().debug("Grammar file '" + grammar.getPath() + "' detected.");
@@ -461,7 +461,7 @@
 
     }
 
-    public Set getIncludesPatterns() {
+    public Set<String> getIncludesPatterns() {
         if (includes == null || includes.isEmpty()) {
             return Collections.singleton("**/*.g");
         }
@@ -471,11 +471,11 @@
     /**
      * Given the source directory File object and the full PATH to a
      * grammar, produce the path to the named grammar file in relative
-     * terms to the sourceDirectory. This will then allow ANTLR to
+     * terms to the {@code sourceDirectory}. This will then allow ANTLR to
      * produce output relative to the base of the output directory and
      * reflect the input organization of the grammar files.
      *
-     * @param sourceDirectory The source directory File object
+     * @param sourceDirectory The source directory {@link File} object
      * @param grammarFileName The full path to the input grammar file
      * @return The path to the grammar file relative to the source directory
      */
@@ -487,7 +487,11 @@
         }
 
         File unprefixedGrammarFileName = new File(grammarFileName.substring(srcPath.length()));
-
-        return unprefixedGrammarFileName.getParent() + File.separator;
+	if ( unprefixedGrammarFileName.getParent()!=null ) {
+	    return unprefixedGrammarFileName.getParent() + File.separator;
+        }
+	else {
+            return "";
+	}
     }
 }
diff --git a/antlr3-maven-plugin/src/site/apt/examples/import.apt b/antlr3-maven-plugin/src/site/apt/examples/import.apt
index 06a49f1..befd508 100644
--- a/antlr3-maven-plugin/src/site/apt/examples/import.apt
+++ b/antlr3-maven-plugin/src/site/apt/examples/import.apt
@@ -1,7 +1,7 @@
 Imported Grammar Files
 
  In order to have the ANTLR plugin automatically locate and use grammars used
- as imports in your main .g files, you need to place the imported grammar
+ as imports in your main <<<.g>>> files, you need to place the imported grammar
  files in the imports directory beneath the root directory of your grammar
  files (which is <<<src/main/antlr3>>> by default of course).
 
diff --git a/antlr3-maven-plugin/src/site/apt/examples/libraries.apt b/antlr3-maven-plugin/src/site/apt/examples/libraries.apt
index 73ce796..822a9ac 100644
--- a/antlr3-maven-plugin/src/site/apt/examples/libraries.apt
+++ b/antlr3-maven-plugin/src/site/apt/examples/libraries.apt
@@ -2,23 +2,23 @@
 
  The introduction of the import directive in a grammar allows reuse of common grammar files
  as well as the ability to divide up functional components of large grammars. However it has
- caused some confusion in regard to the fact that generated vocab files (<<<xxx.tokens>>>) can also
+ caused some confusion in regard to the fact that generated vocabulary files (<<<*.tokens>>>) can also
  be searched for with the <<<<libDirectory>>>> directive.
 
  This has confused two separate functions and imposes a structure upon the layout of
  your grammar files in certain cases. If you have grammars that both use the import
- directive and also require the use of a vocab file then you will need to locate
- the grammar that generates the .tokens file alongside the grammar that uses it. This
+ directive and also require the use of a vocabulary file then you will need to locate
+ the grammar that generates the <<<.tokens>>> file alongside the grammar that uses it. This
  is because you will need to use the <<<<libDirectory>>>> directive to specify the
- location of your imported grammars and ANTLR will not find any vocab files in
+ location of your imported grammars and ANTLR will not find any vocabulary files in
  this directory.
 
- The .tokens files for any grammars are generated within the same output directory structure
- as the .java files. So, whereever the .java files are generated, you will also find the .tokens
- files. ANTLR looks for .tokens files in both the <<<<libDirectory>>>> and the output directory
- where it is placing the geenrated .java files. Hence when you locate the grammars that generate
- .tokens files in the same source directory as the ones that use the .tokens files, then
- the Maven plugin will find the expected .tokens files.
+ The <<<.tokens>>> files for any grammars are generated within the same output directory structure
+ as the <<<.java>>> files. So, wherever the <<<.java>>> files are generated, you will also find the <<<.tokens>>>
+ files. ANTLR looks for <<<.tokens>>> files in both the <<<<libDirectory>>>> and the output directory
+ where it is placing the generated <<<.java>>> files. Hence when you locate the grammars that generate
+ <<<.tokens>>> files in the same source directory as the ones that use the <<<.tokens>>> files, then
+ the Maven plugin will find the expected <<<.tokens>>> files.
 
  The <<<<libDirectory>>>> is specified like any other directory parameter in Maven. Here is an
  example:
@@ -27,10 +27,9 @@
 <plugin>
     <groupId>org.antlr</groupId>
     <artifactId>antlr3-maven-plugin</artifactId>
-    <version>3.1.3-1</version>
+    <version>${plugin.version}</version>
 
     <executions>
-
         <execution>
             <configuration>
                 <goals>
diff --git a/antlr3-maven-plugin/src/site/apt/examples/simple.apt b/antlr3-maven-plugin/src/site/apt/examples/simple.apt
index 3e36e84..ed1918b 100644
--- a/antlr3-maven-plugin/src/site/apt/examples/simple.apt
+++ b/antlr3-maven-plugin/src/site/apt/examples/simple.apt
@@ -1,7 +1,7 @@
 Simple configuration
 
  If your grammar files are organized into the default locations as described in the {{{../index.html}introduction}},
- then configuring the pom.xml file for your project is as simple as adding this to it
+ then configuring the <<<pom.xml>>> file for your project is as simple as adding this to it
 
 +--
 <plugins>
@@ -21,12 +21,12 @@
 </plugins>
 +--
 
- When the mvn command is executed all grammar files under <<<src/main/antlr3>>>, except any
+ When the <<<mvn>>> command is executed all grammar files under <<<src/main/antlr3>>>, except any
  import grammars under <<<src/main/antlr3/imports>>> will be analyzed and converted to
- java source code in the output directory <<<target/generated-sources/antlr3>>>.
+ Java source code in the output directory <<<target/generated-sources/antlr3>>>.
 
  Your input files under <<<antlr3>>> should be stored in sub directories that
- reflect the package structure of your java parsers. If your grammar file parser.g contains:
+ reflect the package structure of your java parsers. If your grammar file <<<parser.g>>> contains:
 
 +---
 @header {
@@ -34,7 +34,7 @@
 }
 +---
 
- Then the .g file should be stored in: <<<src/main/antlr3/org/jimi/themuss/parser.g>>>. THis way
- the generated .java files will correctly reflect the package structure in which they will
+ Then the <<<.g>>> file should be stored in: <<<src/main/antlr3/org/jimi/themuss/parser.g>>>. This way
+ the generated <<<.java>>> files will correctly reflect the package structure in which they will
  finally rest as classes.
 
diff --git a/antlr3-maven-plugin/src/site/apt/faq.apt.vm b/antlr3-maven-plugin/src/site/apt/faq.apt.vm
new file mode 100644
index 0000000..d6360a1
--- /dev/null
+++ b/antlr3-maven-plugin/src/site/apt/faq.apt.vm
@@ -0,0 +1 @@
+FAQ
diff --git a/antlr3-maven-plugin/src/site/apt/index.apt b/antlr3-maven-plugin/src/site/apt/index.apt
index 2b2495a..2b57f13 100644
--- a/antlr3-maven-plugin/src/site/apt/index.apt
+++ b/antlr3-maven-plugin/src/site/apt/index.apt
@@ -28,7 +28,7 @@
  use version 3.1.3 of the plugin, you will build your grammars using version 3.1.3 of the
  ANTLR tool, version 3.2 of the plugin will use version 3.2 of the ANTLR tool and so on.
 
- You may also find that there are patch versions of the plugin suchas 3.1.3-1 3.1.3-2 and
+ You may also find that there are patch versions of the plugin such as 3.1.3-1 3.1.3-2 and
  so on. Use the latest patch release of the plugin.
 
  The current version of the plugin is shown at the top of this page after the <<Last Deployed>> date.
@@ -49,10 +49,10 @@
              +--- imports/  .g files that are imported by other grammars.
 +--
 
- If your grammar is intended to be part of a package called org.foo.bar then you would
+ If your grammar is intended to be part of a package called <<<org.foo.bar>>> then you would
  place it in the directory <<<src/main/antlr3/org/foo/bar>>>. The plugin will then produce
- .java and .tokens files in the output directory <<<target/generated-sources/antlr3/org/foo/bar>>>
- When the Java files are compiled they will be in the correct location for the javac
+ <<<.java>>> and <<<.tokens>>> files in the output directory <<<target/generated-sources/antlr3/org/foo/bar>>>
+ When the Java files are compiled they will be in the correct location for the Javac
  compiler without any special configuration. The generated java files are automatically
  submitted for compilation by the plugin.
 
@@ -60,4 +60,3 @@
  any grammar files that are imported by other grammar files (do not make subdirectories here.)
  Such files are never built on their own, but the plugin will automatically tell the ANTLR
  tool to look in this directory for library files.
-
diff --git a/antlr3-maven-plugin/src/site/apt/usage.apt.vm b/antlr3-maven-plugin/src/site/apt/usage.apt.vm
index 9b7ad0f..1b28890 100644
--- a/antlr3-maven-plugin/src/site/apt/usage.apt.vm
+++ b/antlr3-maven-plugin/src/site/apt/usage.apt.vm
@@ -1,193 +1,59 @@
 Usage
 
- The Maven plugin for antlr is simple to use but is at its simplest when you use the default
- layouts for your grammars, as so:
+ The ANTLR 3 plugin for Maven can generate parsers for any number of grammars in
+ your project.
+
+* Compiling Grammars into Parsers
+
+ By default, the <<<{{{./antlr-mojo.html}antlr}}>>> goal will search for grammar
+ files in the directory <<<$\{basedir\}/src/main/antlr3>>> and any additional
+ <<<.tokens>>> files in the directory <<<$\{basedir\}/src/main/antlr3/imports>>>.
+ This can be configured to search other directories using the plugin configuration
+ parameters as described in the <<<{{{./antlr-mojo.html}antlr}}>>> goal
+ documentation.
+
+ The following figure shows the expected layout of files for the default
+ configuration of this plugin.
 
 +--
  src/main/
       |
-      +--- antlr3/... .g files organized in the required package structure
+      +--- antlr3/...       .g files organized in the required package structure
              |
-             +--- imports/  .g files that are imported by other grammars.
+             +--- imports/  user-created .tokens files and .g files that are imported by other grammars
 +--
 
- However, if you are not able to use this structure for whatever reason, you
- can configure the locations of the grammar files, where library/import files
- are located and where the output files should be generated.
-
-* Plugin Descriptor
-
- The current version of the plugin is shown at the top of this page after the <<Last Deployed>> date.
-
- The full layout of the descriptor (at least, those parts that are not standard Maven things),
- showing the default values of the configuration options, is as follows:
+ The next step is to configure your POM to call the plugin. The goals will
+ normally run during the generate-sources phase of the build. Examples of how to
+ configure your POM can be found on the various examples pages, reachable via
+ the page menu. If you stick with the default values, the snippet below will
+ suffice:
 
 +--
-<plugin>
-    <groupId>org.antlr</groupId>
-    <artifactId>antlr3-maven-plugin</artifactId>
-    <version>3.1.3-1</version>
-
-    <executions>
-        
-        <execution>
-            <configuration>
-                <goals>
-                    <goal>antlr</goal>
-                </goals>
-                <conversionTimeout>10000</conversionTimeout>
-                <debug>false</debug>
-                <dfa>false</dfa>
-                <nfa>false</nfa>
-                <excludes><exclude/></excludes>
-                <includes><include/></includes>
-                <libDirectory>src/main/antlr3/imports</libDirectory>
-                <messageFormat>antlr</messageFormat>
-                <outputDirectory>target/generated-sources/antlr3</outputDirectory>
-                <printGrammar>false</printGrammar>
-                <profile>false</profile>
-                <report>false</report>
-                <sourceDirectory>src/main/antlr3</sourceDirectory>
-                <trace>false</trace>
-                <verbose>true</verbose>
-            </configuration>
-        </execution>
-    </executions>
-
-</plugin>
+<project>
+  ...
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.antlr</groupId>
+        <artifactId>antlr3-maven-plugin</artifactId>
+        <version>${project.version}</version>
+        <executions>
+          <execution>
+            <id>antlr</id>
+            <goals>
+              <goal>antlr</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+    ...
+  </build>
+  ...
+</project>
 +--
 
- Note that you can create multiple executions, and thus build some grammars with different
- options to others (such as setting the debug option for instance).
-
-** Configuration parameters
-
-*** report
-
-    If set to true, then after the tool has processed an input grammar file
-    it will report variaous statistics about the parser, such as information
-    on cyclic DFAs, which rules may use backtracking, and so on.
-
-    default-value="false"
-
-*** printGrammar
-
-    If set to true, then the ANTLR tool will print a version of the input
-    grammar which is devoid of any actions that may be present in the input file.
-
-    default-value = "false"
-
-*** debug
-
-     If set to true, then the code generated by the ANTLR code generator will
-     be set to debug mode. This means that when run, the code will 'hang' and
-     wait for a debug connection on a TCP port (49100 by default).
-     
-     default-value="false"
-     
-*** profile
-
-     If set to true, then then the generated parser will compute and report on
-     profile information at runtime.
-     
-     default-value="false"
-     
-*** nfa
-
-     If set to true then the ANTLR tool will generate a description of the nfa
-     for each rule in <a href="http://www.graphviz.org">Dot format</a>
-     
-     default-value="false"
-     
-    protected boolean nfa;
-    
-*** dfa
-
-     If set to true then the ANTLR tool will generate a description of the DFA
-     for each decision in the grammar in <a href="http://www.graphviz.org">Dot format</a>
-     
-     default-value="false"
-     
-*** trace
-
-     If set to true, the generated parser code will log rule entry and exit points
-     to stdout as an aid to debugging.
-     
-     default-value="false"
-     
-*** messageFormat
-
-     If this parameter is set, it indicates that any warning or error messages returned
-     by ANLTR, shoould be formatted in the specified way. Currently, ANTLR supports the
-     built-in formats of antlr, gnu and vs2005.
-
-     default-value="antlr"
-     
-*** verbose
-
-     If this parameter is set to true, then ANTLR will report all sorts of things
-     about what it is doing such as the names of files and the version of ANTLR and so on.
-     
-     default-value="true"
-     
-*** conversionTimeout
-
-     The number of milliseconds ANTLR will wait for analysis of each
-     alternative in the grammar to complete before giving up. You may raise
-     this value if ANTLR gives up on a complicated alt and tells you that
-     there are lots of ambiguties, but you know that it just needed to spend
-     more time on it. Note that this is an absolute time and not CPU time.
-     
-     default-value="10000"
-     
-*** includes
-
-     Provides an explicit list of all the grammars that should
-     be included in the generate phase of the plugin. Note that the plugin
-     is smart enough to realize that imported grammars should be included but
-     not acted upon directly by the ANTLR Tool.
-     
-     Unless otherwise specified, the include list scans for and includes all
-     files that end in ".g" in any directory beneath src/main/antlr3. Note that
-     this version of the plugin looks for the directory antlr3 and not the directory
-     antlr, so as to avoid clashes and confusion for projects that use both v2 and v3 grammars
-     such as ANTLR itself.
-     
-*** excludes
-
-     Provides an explicit list of any grammars that should be excluded from
-     the generate phase of the plugin. Files listed here will not be sent for
-     processing by the ANTLR tool.
-     
-*** sourceDirectory
-
-     Specifies the Antlr directory containing grammar files. For
-     antlr version 3.x we default this to a directory in the tree
-     called antlr3 because the antlr directory is occupied by version
-     2.x grammars.
-
-     <<NB>> Take careful note that the default location for antlr grammars
-     is now <<antlr3>> and NOT <<antlr>>
-
-     default-value="<<<${basedir}/src/main/antlr3>>>"
-     
-*** outputDirectory
-
-     Location for generated Java files. For antlr version 3.x we default
-     this to a directory in the tree called antlr3 because the antlr
-     directory is occupied by version 2.x grammars.
-     
-     default-value="<<<${project.build.directory}/generated-sources/antlr3>>>"
-     
-*** libDirectory
-
-     Location for imported token files, e.g. <code>.tokens</code> and imported grammars.
-     Note that ANTLR will not try to process grammars that it finds in this directory, but
-     will include this directory in the search for .tokens files and import grammars.
-
-     <<NB>> If you change the lib directory from the default but the directory is
-     still under<<<${basedir}/src/main/antlr3>>>, then you will need to exclude
-     the grammars from processing specifically, using the <<<<excludes>>>> option.
-
-     default-value="<<<${basedir}/src/main/antlr3/imports>>>"
-
+ Note that you can create multiple executions, and thus build some grammars with
+ different options to others (such as setting the <<<debug>>> option for
+ instance).
diff --git a/antlr3-maven-plugin/src/site/site.xml b/antlr3-maven-plugin/src/site/site.xml
index 7d0c52b..92bcea3 100644
--- a/antlr3-maven-plugin/src/site/site.xml
+++ b/antlr3-maven-plugin/src/site/site.xml
@@ -6,18 +6,20 @@
   <version position="left"/>
 
   <poweredBy>
-    <logo name="ANTLR Web Site" href="http://antlr.org/"
+    <logo name="ANTLR Web Site" href="http://antlr3.org/"
           img="http://www.antlr.org/wiki/download/attachments/292/ANTLR3"/>
   </poweredBy>
 
   <body>
     <links>
-      <item name="Antlr Web Site" href="http://www.antlr.org/"/>
+      <item name="Antlr Web Site" href="http://www.antlr3.org/"/>
     </links>
 
     <menu name="Overview">
       <item name="Introduction" href="index.html"/>
+      <item name="Goals" href="plugin-info.html"/>
       <item name="Usage" href="usage.html"/>
+      <item name="FAQ" href="faq.html"/>
     </menu>
 
     <menu name="Examples">
diff --git a/antlrjar.xml b/antlrjar.xml
deleted file mode 100644
index 6988f98..0000000
--- a/antlrjar.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!--
-    This file defines what goes in to ANTLR Uber jar, which includes
-    all of the classes we need to run an executable jar in standalone
-    mode.
-  -->
-<assembly>
-
-    <!--
-        This is the suffix that will be used to name the uber jar
-        once it is jared up.
-      -->
-    <id>completejar</id>
-
-    <!--
-        The only output format we need is the executable jar file
-      -->
-    <formats>
-        <format>jar</format>
-    </formats>
-
-    <!--
-        Make all jars unpack at the same level and don't include
-        any extraneous directories.
-      -->
-    <includeBaseDirectory>false</includeBaseDirectory>
-
-    <!--
-        Which of the modules that the master pom builds do we
-        wish to include in the uber jar. We are including
-        dependencies, so we only need to name the Tool module
-        and the gunit module.
-      -->
-    <moduleSets>
-
-        <moduleSet>
-            
-            <includes>
-                
-                <include>org.antlr:antlr</include>
-          
-            </includes>
-            <!--
-                Of the binaries, such as the dependencies that the
-                above modules need, which do we want and which do we not.
-                Currently we want all the dependencies in the Tool jar.
-              -->
-            <binaries>
-
-                <dependencySets>
-                    <dependencySet>
-                        <!--
-                            Exclude the antlr-master pom from the jar - we don't need it
-                            and it causes silly things to happen.
-                          -->
-                        <useProjectArtifact>false</useProjectArtifact>
-                    
-                        <!--
-                            Unpack the binary dependencies so we have a nice
-                            uber jar that can run with java -jar and need not have
-                            CLASSPATH configured and so on.
-                          -->
-                        <unpack>true</unpack>
-                    </dependencySet>
-                </dependencySets>
-
-
-            </binaries>
-
-        </moduleSet>
-       
-    </moduleSets>
-
-    <!--
-        What do we want to include in the jar from each project
-      -->
-    <fileSets>
-        <fileSet>
-
-            <!--
-                We need the output classes and resources etc.
-              -->
-            <directory>${project.build.outputDirectory}</directory>
-        </fileSet>
-    </fileSets>
-
-</assembly>
diff --git a/antlrsources.xml b/antlrsources.xml
deleted file mode 100644
index 953c7fc..0000000
--- a/antlrsources.xml
+++ /dev/null
@@ -1,172 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!--
-
-    This is the assembly descriptor for building a full source code
-    distribution of ANTLR and all its related components. This assembly
-    only includes the Java oriented source code, hence only the Java runtime
-    is included in the resulting jar.
-
-    The resulting jar is distribution that can be expanded with:
-
-      jar xvf antlr-master-3.x.x-src.jar
-
-    The output directory will be antlr-master-3.x.x and in here will be
-    the BUILD.txt fie, which explains how to build ANTLR.
-
-    Jim Idle - May, 2009
- -->
-<assembly>
-
-    <!-- The name of this assembly descriptor, which is referenced in
-         the master pom.xml using <assemblyRef> (although in fact we
-         reference the file name that contains it to avoid cluttering
-         the pom.
-      -->
-    <id>src</id>
-
-    <!-- We have elected to produce only a jar output and to use the line
-         endings of whatever platform we are running on. More formats
-         can be added for simultaneous production, such as <format>zip</format>
-      -->
-    <formats>
-        <format>jar</format>
-    </formats>
-
-    <!--
-        The resulting archives will have a base directory named after the master
-        artifact, rather than just extract into the current directory.
-      -->
-    <includeBaseDirectory>true</includeBaseDirectory>
-
-    <!-- We need to described the source code of each of the modules we want
-         including in the archive. In the main this is because we did not store
-         the modules in perforce using directory names that match the module
-         names. This was for historic reasons as we already moved everything
-         about massively, just to move to Maven in the first place.
-      -->
-    <moduleSets>
-
-        <!-- Describe the gUnit source code.
-          -->
-        <moduleSet>
-
-            <!-- The Maven artifact name tells the assembly artifact a bunch
-                 of information to start with, such as its location in the current
-                 tree and so on.
-              -->
-            <includes>
-                <include>org.antlr:antlr-runtime</include>
-            </includes>
-
-            <!-- What sources do we wish to include from this module?
-              -->
-            <sources>
-
-                <!-- Because the Java runtime source is not in a directory
-                     called antlr-runtime, directly underneath the master
-                     directory, we need to map the output directory so that
-                     instead of starting with the name of the artifact, it
-                     is in the place where the build expects it.
-                  -->
-                <outputDirectoryMapping>runtime/Java</outputDirectoryMapping>
-
-                <fileSets>
-                     <!-- We have one file set, being the src sub-directory, which in
-                          the output archive, we also want to be called src/
-                       -->
-                    <fileSet>
-                        <directory>src</directory>
-                        <outputDirectory>src</outputDirectory>
-                    </fileSet>
-
-                    <!-- In the base runtime/Java directory, we need to include a number
-                         of files that either document the module or control the
-                         build. These are not underneath the src directory of course
-                         so they need to be named here (which nicely documents what
-                         is included.
-                      -->
-                    <fileSet>
-                        <includes>
-                            <include>pom.xml</include>
-                            <include>doxyfile</include>
-                            <include>antlr.config</include>
-                        </includes>
-                    </fileSet>
-                </fileSets>
-            </sources>
-
-        </moduleSet>
-
-        <!-- Describe the ANTLR tool source code.
-          -->
-        <moduleSet>
-            <includes>
-                <include>org.antlr:antlr</include>
-            </includes>
-
-            <!-- What sources do we wish to include from this module?
-              -->
-            <sources>
-
-                <!-- Because the tool source code is not in a directory
-                     called antlr, nor directly underneath the master
-                     directory, we need to map the output directory so that
-                     instead of starting with the name of the artifact, it
-                     is in the place where the build expects it.
-                  -->
-                <outputDirectoryMapping>tool</outputDirectoryMapping>
-
-
-                <fileSets>
-
-                    <!-- We have one file set, being the src sub-directory, which in
-                         the output archive, we also want to be called src/
-                      -->
-                    <fileSet>
-                        <directory>src</directory>
-                        <outputDirectory>src</outputDirectory>
-                    </fileSet>
-
-                    <!-- In the base tool directory, we need to include a number
-                         of files that either document the module or control the
-                         build. These are not underneath the src directory of course
-                         so they need to be named here (which nicely documents what
-                         is included.
-                      -->
-                    <fileSet>
-                        <includes>
-                            <include>pom.xml</include>
-                            <include>CHANGES.txt</include>
-                            <include>LICENSE.txt</include>
-                            <include>README.txt</include>
-                            <include>antlr.config</include>
-                        </includes>
-                    </fileSet>
-
-                </fileSets>
-
-            </sources>
-
-        </moduleSet>
-
-    </moduleSets>
-
-    <!-- In the base directory of the master build directory (the root of all
-         the other sources), there are a number of files that describe or control
-         the build (such as the master pom.xml and the BUILD.txt files). Hence
-         we need to describe them in their own fileset. No output mapping is required here
-         of course.
-      -->
-    <fileSets>
-        <fileSet>
-            <includes>
-                <include>pom.xml</include>
-                <include>antlrjar.xml</include>
-                <include>antlrsources.xml</include>
-                <include>BUILD.txt</include>
-            </includes>
-        </fileSet>
-    </fileSets>
-
-</assembly>
diff --git a/contributors.txt b/contributors.txt
new file mode 100644
index 0000000..c5d133d
--- /dev/null
+++ b/contributors.txt
@@ -0,0 +1,59 @@
+ANTLR Project Contributors Certification of Origin and Rights
+
+All contributors to ANTLR v3 must formally agree to abide by this
+certificate of origin by signing on the bottom with their github
+userid, full name, email address (you can obscure your e-mail, but it
+must be computable by human), and date.
+
+By signing this agreement, you are warranting and representing that
+you have the right to release code contributions or other content free
+of any obligations to third parties and are granting Terence Parr and
+ANTLR project contributors, henceforth referred to as The ANTLR
+Project, a license to incorporate it into The ANTLR Project tools
+(such as ANTLRWorks and StringTemplate) or related works under the BSD
+license. You understand that The ANTLR Project may or may not
+incorporate your contribution and you warrant and represent the
+following:
+
+1. I am the creator of all my contributions. I am the author of all
+   contributed work submitted and further warrant and represent that
+   such work is my original creation and I have the right to license
+   it to The ANTLR Project for release under the 3-clause BSD
+   license. I hereby grant The ANTLR Project a nonexclusive,
+   irrevocable, royalty-free, worldwide license to reproduce,
+   distribute, prepare derivative works, and otherwise use this
+   contribution as part of the ANTLR project, associated
+   documentation, books, and tools at no cost to The ANTLR Project.
+
+2. I have the right to submit. This submission does not violate the
+   rights of any person or entity and that I have legal authority over
+   this submission and to make this certification.
+
+3. If I violate another's rights, liability lies with me. I agree to
+   defend, indemnify, and hold The ANTLR Project and ANTLR users
+   harmless from any claim or demand, including reasonable attorney
+   fees, made by any third party due to or arising out of my violation
+   of these terms and conditions or my violation of the rights of
+   another person or entity.
+
+4. I understand and agree that this project and the contribution are
+   public and that a record of the contribution (including all
+   personal information I submit with it, including my sign-off) is
+   maintained indefinitely and may be redistributed consistent with
+   this project or the open source license indicated in the file.
+
+I have read this agreement and do so certify by adding my signoff to
+the end of the following contributors list.
+
+CONTRIBUTORS:
+
+YYYY/MM/DD, github id, Full name, email
+2013/04/17, ibre5041, Ivan Brezina, ibre5041@ibrezina.net
+2013/02/19, murrayju, Justin Murray, murrayju@addpcs.com
+2012/07/12, parrt, Terence Parr, parrt@antlr.org
+2012/08/08, Zannick, Benjamin S Wolf, jokeserver@gmail.com
+2012/09/15, martint, Martin Traverso, mtraverso@gmail.com
+2012/09/16, qmx, Douglas Campos, qmx@qmx.me
+2012/09/17, ksgokul, Gokulakannan Somasundaram, gokul007@gmail.com
+2012/11/22, sharwell, Sam Harwell, sam@tunnelvisionlabs.com
+2012/09/24, mike-lischke, Mike Lischke, mike@lischke-online.de
diff --git a/gunit-maven-plugin/antlr.config b/gunit-maven-plugin/antlr.config
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/gunit-maven-plugin/antlr.config
diff --git a/gunit-maven-plugin/pom.xml b/gunit-maven-plugin/pom.xml
index a11a50e..1a50e34 100644
--- a/gunit-maven-plugin/pom.xml
+++ b/gunit-maven-plugin/pom.xml
@@ -31,25 +31,8 @@
 
   -->
 
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
-    <!--
-        The ANTLR Maven artifacts are now released via the Sonotype OSS
-        repository, which means that they are synced to Maven central 
-        within a few minutes of hitting the release repo for Sonotype.
-        To enable this, we inherit from the Sonotype provided parent
-        pom. However, we must also configure our .m2/settings.xml to include
-        the snapshot and staging server and the sonotype password. This 
-        means that only ANTLR developers can released the artifacts, but
-        anyone can build locally.
-      -->
-    <parent>
-        <groupId>org.sonatype.oss</groupId>
-        <artifactId>oss-parent</artifactId>
-        <version>7</version>
-    </parent> 
-    
     <modelVersion>4.0.0</modelVersion>
 
     <prerequisites>
@@ -59,86 +42,27 @@
     <groupId>org.antlr</groupId>
     <artifactId>maven-gunit-plugin</artifactId>
     <packaging>maven-plugin</packaging>
-    <version>3.4</version>
 
-    <name>Maven plugin for gUnit ANTLR V3.4</name>
+    <name>ANTLR 3 gUnit Maven plugin</name>
 	<description>A Maven plugin for incorporating gUnit testing of grammars</description>
     <url>http://antlr.org</url>
 
+    <!--
+
+    Inherit from the ANTLR master pom, which tells us what
+    version we are and allows us to inherit dependencies
+    and so on.
+    -->
+    <parent>
+        <groupId>org.antlr</groupId>
+        <artifactId>antlr-master</artifactId>
+        <version>3.5.2</version>
+    </parent>
+
     <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     </properties>
 
-    <!-- Where do we track bugs for this project?
-      -->
-    <issueManagement>
-        <system>JIRA</system>
-        <url>http://antlr.org/jira/browse/ANTLR</url>
-    </issueManagement>
-
-    <!-- Location of the license description for this project
-      -->
-    <licenses>
-        <license>
-            <distribution>repo</distribution>
-            <name>The BSD License</name>
-            <url>http://www.antlr.org/LICENSE.txt </url>
-        </license>
-    </licenses>
-
-    <profiles>
-        <profile>
-            <id>release-sign-artifacts</id>
-            <activation>
-                <property>
-                    <name>deploy</name>
-                    <value>true</value>
-                </property>
-            </activation>
-            <build>
-                <plugins>
-                    <plugin>
-                        <groupId>org.apache.maven.plugins</groupId>
-                        <artifactId>maven-gpg-plugin</artifactId>
-                        <version>1.3</version>
-                        <executions>
-                            <execution>
-                                <id>sign-artifacts</id>
-                                <phase>verify</phase>
-                                <goals>
-                                   <goal>sign</goal>
-                                </goals>
-                            </execution>
-                        </executions>
-                    </plugin>
-                </plugins>
-            </build>
-        </profile>
-    </profiles>
-    
-    <!-- Ancilliary information for completeness
-      -->
-    <inceptionYear>2009</inceptionYear>
-
-    <mailingLists>
-        <mailingList>
-            <archive>http://antlr.markmail.org/</archive>
-            <otherArchives>
-                <otherArchive>http://www.antlr.org/pipermail/antlr-interest/</otherArchive>
-            </otherArchives>
-            <name>ANTLR Users</name>
-            <subscribe>http://www.antlr.org/mailman/listinfo/antlr-interest/</subscribe>
-            <unsubscribe>http://www.antlr.org/mailman/options/antlr-interest/</unsubscribe>
-            <post>antlr-interest@antlr.org</post>
-        </mailingList>
-    </mailingLists>
-
-    <organization>
-        <name>ANTLR.org</name>
-        <url>http://www.antlr.org</url>
-    </organization>
-    <!-- ============================================================================= -->
-
     <!--
 
      What are we depedent on for the Mojos to execute? We need the
@@ -167,7 +91,7 @@
         <dependency>
             <groupId>org.codehaus.plexus</groupId>
             <artifactId>plexus-compiler-api</artifactId>
-            <version>1.5.3</version>
+            <version>2.0</version>
         </dependency>
 
         <!--
@@ -178,34 +102,22 @@
         <dependency>
             <groupId>org.antlr</groupId>
             <artifactId>antlr</artifactId>
-            <version>3.4</version>
+            <version>${project.version}</version>
         </dependency>
 
         <!--
          Dependency on the gUnit artifact.
         -->
         <dependency>
-            <groupId>${groupId}</groupId>
+            <groupId>org.antlr</groupId>
             <artifactId>gunit</artifactId>
-            <version>3.4</version>
-        </dependency>
-
-        <!--
-          Testing requirements...
-          -->
-        <dependency>
-
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <version>4.8.2</version>
-            <scope>test</scope>
-
+            <version>${project.version}</version>
         </dependency>
 
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-plugin-testing-harness</artifactId>
-            <version>1.0</version>
+            <version>1.1</version>
             <scope>test</scope>
         </dependency>
         
@@ -213,55 +125,17 @@
     
     <build>
 
-        <defaultGoal>install</defaultGoal>
         <plugins>
-            
-            <plugin>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <version>2.0.2</version>
-                <configuration>
-                    <source>1.6</source>
-                    <target>jsr14</target>
-                </configuration>
-            </plugin>
-            
+
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-project-info-reports-plugin</artifactId>
-                <version>2.4</version>
+                <version>2.6</version>
                 <configuration>
                     <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
                 </configuration>
             </plugin>
 
-            <plugin>  
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-source-plugin</artifactId>
-                <version>2.1.2</version>
-                <executions>
-                    <execution>
-                        <id>attach-sources</id>
-                        <goals>
-                            <goal>jar</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-			
-            <plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-javadoc-plugin</artifactId>
-                <version>2.8</version>
-				<executions>
-					<execution>
-						<id>attach-javadocs</id>
-						<goals>
-							<goal>jar</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-            
         </plugins>
 
     </build>
diff --git a/gunit-maven-plugin/src/main/java/org/antlr/mojo/antlr3/GUnitExecuteMojo.java b/gunit-maven-plugin/src/main/java/org/antlr/mojo/antlr3/GUnitExecuteMojo.java
index db3f569..a7e2317 100644
--- a/gunit-maven-plugin/src/main/java/org/antlr/mojo/antlr3/GUnitExecuteMojo.java
+++ b/gunit-maven-plugin/src/main/java/org/antlr/mojo/antlr3/GUnitExecuteMojo.java
@@ -85,14 +85,14 @@
      *
      * @parameter
      */
-    private Set includes;
+    private Set<String> includes;
 
     /**
      * A set of exclude patterns.
      *
      * @parameter
      */
-    private Set excludes;
+    private Set<String> excludes;
 
 	/**
      * Specifies directory to which gUnit reports should get written.
@@ -104,22 +104,22 @@
 
 	/**
 	 * Should gUnit functionality be completely by-passed?
-	 * <p/>
-	 * By default we skip gUnit tests if the user requested that all testing be skipped using 'maven.test.skip'
+	 * <p>
+	 * By default we skip gUnit tests if the user requested that all testing be skipped using 'maven.test.skip'</p>
 	 *
 	 * @parameter expression="${maven.test.skip}"
 	 */
 	private boolean skip;
 
-	public Set getIncludePatterns() {
+	public Set<String> getIncludePatterns() {
 		return includes == null || includes.isEmpty()
 				? Collections.singleton( "**/*.testsuite" )
 				: includes;
 	}
 
-	public Set getExcludePatterns() {
+	public Set<String> getExcludePatterns() {
 		return excludes == null
-				? Collections.emptySet()
+				? Collections.<String>emptySet()
 				: excludes;
 	}
 
@@ -346,24 +346,11 @@
 	}
 
 	private Set<File> collectIncludedSourceGrammars() throws MojoExecutionException {
-		SourceMapping mapping = new SuffixMapping( "g", Collections.EMPTY_SET );
+		SourceMapping mapping = new SuffixMapping( "g", Collections.<String>emptySet() );
         SourceInclusionScanner scan = new SimpleSourceInclusionScanner( getIncludePatterns(), getExcludePatterns() );
         scan.addSourceMapping( mapping );
 		try {
-			Set scanResults = scan.getIncludedSources( sourceDirectory, null );
-			Set<File> results = new HashSet<File>();
-			for ( Object result : scanResults ) {
-				if ( result instanceof File ) {
-					results.add( ( File ) result );
-				}
-				else if ( result instanceof String ) {
-					results.add( new File( ( String ) result ) );
-				}
-				else {
-					throw new MojoExecutionException( "Unexpected result type from scanning [" + result.getClass().getName() + "]" );
-				}
-			}
-			return results;
+			return scan.getIncludedSources( sourceDirectory, null );
 		}
 		catch ( InclusionScanException e ) {
 			throw new MojoExecutionException( "Error determining gUnit sources", e );
diff --git a/gunit/pom.xml b/gunit/pom.xml
index cb35b6b..8a8da9e 100644
--- a/gunit/pom.xml
+++ b/gunit/pom.xml
@@ -1,11 +1,12 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
-    <groupId>org.antlr</groupId>
     <artifactId>gunit</artifactId>
     <packaging>jar</packaging>
   
-    <name>ANTLR gUnit v3.4</name>
+    <name>ANTLR 3 gUnit</name>
+    <description>gUnit grammar testing tool for ANTLR 3</description>
+
   <!--
 
     Inherit from the ANTLR master pom, which tells us what
@@ -16,11 +17,11 @@
     <parent>
         <groupId>org.antlr</groupId>
         <artifactId>antlr-master</artifactId>
-        <version>3.4</version>
+        <version>3.5.2</version>
     </parent>
 
     <url>http://www.antlr.org/wiki/display/ANTLR3/gUnit+-+Grammar+Unit+Testing</url>
-  
+
   <!--
 
     Tell Maven which other artifacts we need in order to
@@ -37,7 +38,6 @@
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
-            <version>4.8.2</version>
             <scope>compile</scope>
         </dependency>
 
@@ -48,34 +48,24 @@
             <scope>compile</scope>
             
         </dependency>
-
-        <dependency>
-            <groupId>org.antlr</groupId>
-            <artifactId>ST4</artifactId>
-            <version>4.0.4</version>
-            <scope>compile</scope>
-        </dependency>
-
+        
         <dependency>
             <groupId>org.antlr</groupId>
             <artifactId>stringtemplate</artifactId>
-            <version>3.2.1</version>
             <scope>compile</scope>
         </dependency>
-        
+
     </dependencies>
 
     <build>
 
-        <defaultGoal>install</defaultGoal>
-
         <plugins>
 
             <plugin>
                 <groupId>org.antlr</groupId>
                 <artifactId>antlr3-maven-plugin</artifactId>
                 <version>${project.version}</version>
-                <configuration></configuration>
+                <configuration />
                 <executions>
                     <execution>
                         <goals>
@@ -85,42 +75,8 @@
                 </executions>
             </plugin>
 
-            <plugin>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                    <source>1.6</source>
-                    <target>jsr14</target>
-                    <sourceDirectory>src</sourceDirectory>
-                </configuration>
-            </plugin>
-
-            <plugin>
-                <artifactId>maven-surefire-plugin</artifactId>
-                <version>2.9</version>
-            </plugin>
-
-            <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>findbugs-maven-plugin</artifactId>
-                <version>2.3.2</version>
-                <configuration>
-                    <findbugsXmlOutput>true</findbugsXmlOutput>
-                    <findbugsXmlWithMessages>true</findbugsXmlWithMessages>
-                    <xmlOutput>true</xmlOutput>
-                </configuration>
-            </plugin>
-
         </plugins>
 
-        <extensions>
-            <extension>
-                <groupId>org.apache.maven.wagon</groupId>
-                <artifactId>wagon-ssh-external</artifactId>
-                <version>1.0-beta-2</version>
-            </extension>
-        </extensions>
-
-    
     </build>
 
 </project>
diff --git a/gunit/src/main/antlr3/org/antlr/gunit/swingui/parsers/StGUnit.g b/gunit/src/main/antlr3/org/antlr/gunit/swingui/parsers/StGUnit.g
index 1701214..e645f62 100644
--- a/gunit/src/main/antlr3/org/antlr/gunit/swingui/parsers/StGUnit.g
+++ b/gunit/src/main/antlr3/org/antlr/gunit/swingui/parsers/StGUnit.g
@@ -76,17 +76,17 @@
 	;
 	
 expect returns [ITestCaseOutput out]
-	:	OK			{$out = adapter.createBoolOutput(true);}
-	|	FAIL		{$out = adapter.createBoolOutput(false);}
-	|	'returns' RETVAL {$out = adapter.createReturnOutput($RETVAL.text);}
-	|	'->' output {$out = adapter.createStdOutput($output.text);}
-	|	'->' AST	{$out = adapter.createAstOutput($AST.text);}
+	:	OK			{$out = TestSuiteAdapter.createBoolOutput(true);}
+	|	FAIL		{$out = TestSuiteAdapter.createBoolOutput(false);}
+	|	'returns' RETVAL {$out = TestSuiteAdapter.createReturnOutput($RETVAL.text);}
+	|	'->' output {$out = TestSuiteAdapter.createStdOutput($output.text);}
+	|	'->' AST	{$out = TestSuiteAdapter.createAstOutput($AST.text);}
 	;
 
 input returns [ITestCaseInput in]
-	:	STRING 		{$in = adapter.createStringInput($STRING.text);}
-	|	ML_STRING	{$in = adapter.createMultiInput($ML_STRING.text);}
-	|	fileInput	{$in = adapter.createFileInput($fileInput.path);}
+	:	STRING 		{$in = TestSuiteAdapter.createStringInput($STRING.text);}
+	|	ML_STRING	{$in = TestSuiteAdapter.createMultiInput($ML_STRING.text);}
+	|	fileInput	{$in = TestSuiteAdapter.createFileInput($fileInput.path);}
 	;
 
 output
diff --git a/gunit/src/main/java/org/antlr/gunit/AbstractTest.java b/gunit/src/main/java/org/antlr/gunit/AbstractTest.java
index 158bf04..9d2c8ec 100644
--- a/gunit/src/main/java/org/antlr/gunit/AbstractTest.java
+++ b/gunit/src/main/java/org/antlr/gunit/AbstractTest.java
@@ -63,7 +63,7 @@
 	public String getTestedRuleName() { return this.testedRuleName; }
 	public int getTestCaseIndex() { return this.testCaseIndex; }
 	
-	public void setHeader(String rule, String lexicalRule, String treeRule, int numOfTest, int line) {
+	public void setHeader(String rule, String lexicalRule, String treeRule, int numOfTest, int line, String input) {
 		StringBuffer buf = new StringBuffer();
 		buf.append("test" + numOfTest + " (");
 		if ( treeRule!=null ) {
@@ -73,6 +73,9 @@
 			buf.append(lexicalRule + ", line"+line+")" + " - ");
 		}
 		else buf.append(rule + ", line"+line+")" + " - ");
+		buf.append( "\"" );
+		buf.append( input );
+		buf.append( "\"" );
 		this.header = buf.toString();
 	}
 	public void setActual(String actual) { this.actual = actual; }
diff --git a/gunit/src/main/java/org/antlr/gunit/JUnitCodeGen.java b/gunit/src/main/java/org/antlr/gunit/JUnitCodeGen.java
index 4713cf7..ed5282e 100644
--- a/gunit/src/main/java/org/antlr/gunit/JUnitCodeGen.java
+++ b/gunit/src/main/java/org/antlr/gunit/JUnitCodeGen.java
@@ -73,7 +73,7 @@
         this.testsuiteDir = testsuiteDir;
         /** Map the name of rules having return value to its return type */
         ruleWithReturn = new HashMap<String, String>();
-        Class parserClass = locateParserClass( grammarInfo, classLoader );
+        Class<?> parserClass = locateParserClass( grammarInfo, classLoader );
         Method[] methods = parserClass.getDeclaredMethods();
         for(Method method : methods) {
             if ( !method.getReturnType().getName().equals("void") ) {
@@ -82,7 +82,7 @@
         }
     }
 
-    private Class locateParserClass(GrammarInfo grammarInfo, ClassLoader classLoader) throws ClassNotFoundException {
+    private Class<?> locateParserClass(GrammarInfo grammarInfo, ClassLoader classLoader) throws ClassNotFoundException {
         String parserClassName = grammarInfo.getGrammarName() + "Parser";
         if ( grammarInfo.getGrammarPackage() != null ) {
             parserClassName = grammarInfo.getGrammarPackage()+ "." + parserClassName;
@@ -189,13 +189,14 @@
     private void genParserMethods(StringTemplateGroup group, StringBuffer buf) {
         for ( gUnitTestSuite ts: grammarInfo.getRuleTestSuites() ) {
             int i = 0;
-            for ( gUnitTestInput input: ts.testSuites.keySet() ) {	// each rule may contain multiple tests
+            for ( Map.Entry<gUnitTestInput, AbstractTest> entry : ts.testSuites.entrySet() ) {	// each rule may contain multiple tests
+                gUnitTestInput input = entry.getKey();
                 i++;
                 StringTemplate testRuleMethodST;
                 /** If rule has multiple return values or ast*/
-                if ( ts.testSuites.get(input).getType()== gUnitParser.ACTION && ruleWithReturn.containsKey(ts.getRuleName()) ) {
+                if ( entry.getValue().getType()== gUnitParser.ACTION && ruleWithReturn.containsKey(ts.getRuleName()) ) {
                     testRuleMethodST = group.getInstanceOf("testRuleMethod2");
-                    String outputString = ts.testSuites.get(input).getText();
+                    String outputString = entry.getValue().getText();
                     testRuleMethodST.setAttribute("methodName", "test"+changeFirstCapital(ts.getRuleName())+i);
                     testRuleMethodST.setAttribute("testRuleName", '"'+ts.getRuleName()+'"');
                     testRuleMethodST.setAttribute("test", input);
@@ -208,21 +209,21 @@
                     if ( ts.isLexicalRule() ) testRuleName = ts.getLexicalRuleName();
                     else testRuleName = ts.getRuleName();
                     testRuleMethodST = group.getInstanceOf("testRuleMethod");
-                    String outputString = ts.testSuites.get(input).getText();
+                    String outputString = entry.getValue().getText();
                     testRuleMethodST.setAttribute("isLexicalRule", ts.isLexicalRule());
                     testRuleMethodST.setAttribute("methodName", "test"+changeFirstCapital(testRuleName)+i);
                     testRuleMethodST.setAttribute("testRuleName", '"'+testRuleName+'"');
                     testRuleMethodST.setAttribute("test", input);
-                    testRuleMethodST.setAttribute("tokenType", getTypeString(ts.testSuites.get(input).getType()));
+                    testRuleMethodST.setAttribute("tokenType", getTypeString(entry.getValue().getType()));
 
                     // normalize whitespace
                     outputString = normalizeTreeSpec(outputString);
 
-                    if ( ts.testSuites.get(input).getType()==gUnitParser.ACTION ) {	// trim ';' at the end of ACTION if there is...
+                    if ( entry.getValue().getType()==gUnitParser.ACTION ) {	// trim ';' at the end of ACTION if there is...
                         //testRuleMethodST.setAttribute("expecting", outputString.substring(0, outputString.length()-1));
                         testRuleMethodST.setAttribute("expecting", outputString);
                     }
-                    else if ( ts.testSuites.get(input).getType()==gUnitParser.RETVAL ) {	// Expected: RETVAL
+                    else if ( entry.getValue().getType()==gUnitParser.RETVAL ) {	// Expected: RETVAL
                         testRuleMethodST.setAttribute("expecting", outputString);
                     }
                     else {	// Attach "" to expected STRING or AST
@@ -239,13 +240,14 @@
     private void genTreeMethods(StringTemplateGroup group, StringBuffer buf) {
         for ( gUnitTestSuite ts: grammarInfo.getRuleTestSuites() ) {
             int i = 0;
-            for ( gUnitTestInput input: ts.testSuites.keySet() ) {	// each rule may contain multiple tests
+            for ( Map.Entry<gUnitTestInput, AbstractTest> entry : ts.testSuites.entrySet() ) {	// each rule may contain multiple tests
+                gUnitTestInput input = entry.getKey();
                 i++;
                 StringTemplate testRuleMethodST;
                 /** If rule has multiple return values or ast*/
-                if ( ts.testSuites.get(input).getType()== gUnitParser.ACTION && ruleWithReturn.containsKey(ts.getTreeRuleName()) ) {
+                if ( entry.getValue().getType()== gUnitParser.ACTION && ruleWithReturn.containsKey(ts.getTreeRuleName()) ) {
                     testRuleMethodST = group.getInstanceOf("testTreeRuleMethod2");
-                    String outputString = ts.testSuites.get(input).getText();
+                    String outputString = entry.getValue().getText();
                     testRuleMethodST.setAttribute("methodName", "test"+changeFirstCapital(ts.getTreeRuleName())+"_walks_"+
                                                                 changeFirstCapital(ts.getRuleName())+i);
                     testRuleMethodST.setAttribute("testTreeRuleName", '"'+ts.getTreeRuleName()+'"');
@@ -256,19 +258,19 @@
                 }
                 else {
                     testRuleMethodST = group.getInstanceOf("testTreeRuleMethod");
-                    String outputString = ts.testSuites.get(input).getText();
+                    String outputString = entry.getValue().getText();
                     testRuleMethodST.setAttribute("methodName", "test"+changeFirstCapital(ts.getTreeRuleName())+"_walks_"+
                                                                 changeFirstCapital(ts.getRuleName())+i);
                     testRuleMethodST.setAttribute("testTreeRuleName", '"'+ts.getTreeRuleName()+'"');
                     testRuleMethodST.setAttribute("testRuleName", '"'+ts.getRuleName()+'"');
                     testRuleMethodST.setAttribute("test", input);
-                    testRuleMethodST.setAttribute("tokenType", getTypeString(ts.testSuites.get(input).getType()));
+                    testRuleMethodST.setAttribute("tokenType", getTypeString(entry.getValue().getType()));
 
-                    if ( ts.testSuites.get(input).getType()==gUnitParser.ACTION ) {	// trim ';' at the end of ACTION if there is...
+                    if ( entry.getValue().getType()==gUnitParser.ACTION ) {	// trim ';' at the end of ACTION if there is...
                         //testRuleMethodST.setAttribute("expecting", outputString.substring(0, outputString.length()-1));
                         testRuleMethodST.setAttribute("expecting", outputString);
                     }
-                    else if ( ts.testSuites.get(input).getType()==gUnitParser.RETVAL ) {	// Expected: RETVAL
+                    else if ( entry.getValue().getType()==gUnitParser.RETVAL ) {	// Expected: RETVAL
                         testRuleMethodST.setAttribute("expecting", outputString);
                     }
                     else {	// Attach "" to expected STRING or AST
diff --git a/gunit/src/main/java/org/antlr/gunit/gUnitBaseTest.java b/gunit/src/main/java/org/antlr/gunit/gUnitBaseTest.java
index bf089c3..2b3b085 100644
--- a/gunit/src/main/java/org/antlr/gunit/gUnitBaseTest.java
+++ b/gunit/src/main/java/org/antlr/gunit/gUnitBaseTest.java
@@ -29,37 +29,30 @@
 
 import junit.framework.TestCase;
 import org.antlr.runtime.*;
-import org.antlr.runtime.tree.CommonTree;
-import org.antlr.runtime.tree.CommonTreeNodeStream;
-import org.antlr.runtime.tree.TreeAdaptor;
-import org.antlr.runtime.tree.TreeNodeStream;
+import org.antlr.runtime.tree.*;
 import org.antlr.stringtemplate.StringTemplate;
 
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
+import java.io.*;
+import java.lang.reflect.*;
 
-/** All gUnit-generated JUnit class should extend this class 
+/** All gUnit-generated JUnit class should extend this class
  *  which implements the essential methods for triggering
  *  ANTLR parser/tree walker
  */
 public abstract class gUnitBaseTest extends TestCase {
-	
+
 	public String treeAdaptorPath;
 	public String packagePath;
 	public String lexerPath;
 	public String parserPath;
 	public String treeParserPath;
-	
+
 	protected String stdout;
 	protected String stderr;
-	
+
 	private PrintStream console = System.out;
 	private PrintStream consoleErr = System.err;
-	
+
 	// Invoke target lexer.rule
 	public String execLexer(String testRuleName, int line, String testInput, boolean isFile) throws Exception {
 		CharStream input;
@@ -77,20 +70,18 @@
 		else {
 			input = new ANTLRStringStream(testInput);
 		}
-		Class lexer = null;
+		Class<? extends Lexer> lexer;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
         try {
             /** Use Reflection to create instances of lexer and parser */
-        	lexer = Class.forName(lexerPath);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);        
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args   
-            Lexer lexObj = (Lexer)lexConstructor.newInstance(lexArgs);				// makes new instance of lexer    
+        	lexer = Class.forName(lexerPath).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
             input.setLine(line);
 
-            Method ruleName = lexer.getMethod("m"+testRuleName, new Class[0]);
-            
+            Method ruleName = lexer.getMethod("m"+testRuleName);
+
             /** Start of I/O Redirecting */
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayOutputStream err = new ByteArrayOutputStream();
@@ -102,15 +93,15 @@
 
             /** Invoke lexer rule, and get the current index in CharStream */
             ruleName.invoke(lexObj, new Object[0]);
-            Method ruleName2 = lexer.getMethod("getCharIndex", new Class[0]);
+            Method ruleName2 = lexer.getMethod("getCharIndex");
             int currentIndex = (Integer) ruleName2.invoke(lexObj, new Object[0]);
             if ( currentIndex!=input.size() ) {
             	ps2.println("extra text found, '"+input.substring(currentIndex, input.size()-1)+"'");
             }
-			
+
             this.stdout = null;
 			this.stderr = null;
-            
+
 			if ( err.toString().length()>0 ) {
 				this.stderr = err.toString();
 				return this.stderr;
@@ -122,17 +113,17 @@
 				return null;
 			}
         } catch (ClassNotFoundException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (SecurityException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (NoSuchMethodException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (IllegalArgumentException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (InstantiationException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (IllegalAccessException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
         } catch (InvocationTargetException e) {	// This exception could be caused from ANTLR Runtime Exception, e.g. MismatchedTokenException
         	if ( e.getCause()!=null ) this.stderr = e.getCause().toString();
 			else this.stderr = e.toString();
@@ -149,9 +140,9 @@
         }
         return this.stdout;
 	}
-	
+
 	// Invoke target parser.rule
-	
+
 	public Object execParser(String testRuleName, int line, String testInput, boolean isFile) throws Exception {
 		CharStream input;
 		/** Set up ANTLR input stream based on input source, file or String */
@@ -168,33 +159,28 @@
 		else {
 			input = new ANTLRStringStream(testInput);
 		}
-		Class lexer = null;
-		Class parser = null;
+		Class<? extends Lexer> lexer;
+		Class<? extends Parser> parser;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
         ByteArrayOutputStream out = null;
         ByteArrayOutputStream err = null;
 		try {
 			/** Use Reflection to create instances of lexer and parser */
-			lexer = Class.forName(lexerPath);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args   
-            Lexer lexObj = (Lexer)lexConstructor.newInstance(lexArgs);				// makes new instance of lexer
+			lexer = Class.forName(lexerPath).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
             input.setLine(line);
 
             CommonTokenStream tokens = new CommonTokenStream(lexObj);
-            parser = Class.forName(parserPath);
-            Class[] parArgTypes = new Class[]{TokenStream.class};				// assign type to parser's args
-            Constructor parConstructor = parser.getConstructor(parArgTypes);
-            Object[] parArgs = new Object[]{tokens};							// assign value to parser's args  
-            Parser parObj = (Parser)parConstructor.newInstance(parArgs);				// makes new instance of parser
-            
+            parser = Class.forName(parserPath).asSubclass(Parser.class);
+            Constructor<? extends Parser> parConstructor = parser.getConstructor(TokenStream.class);
+            Parser parObj = parConstructor.newInstance(tokens);				// makes new instance of parser
+
             // set up customized tree adaptor if necessary
             if ( treeAdaptorPath!=null ) {
-            	parArgTypes = new Class[]{TreeAdaptor.class};
-            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", parArgTypes);
-            	Class _treeAdaptor = Class.forName(treeAdaptorPath);
+            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", TreeAdaptor.class);
+            	Class<? extends TreeAdaptor> _treeAdaptor = Class.forName(treeAdaptorPath).asSubclass(TreeAdaptor.class);
             	_setTreeAdaptor.invoke(parObj, _treeAdaptor.newInstance());
             }
 
@@ -217,7 +203,7 @@
             if ( ruleReturn!=null ) {
                 if ( ruleReturn.getClass().toString().indexOf(testRuleName+"_return")>0 ) {
                 	try {	// NullPointerException may happen here...
-                		Class _return = Class.forName(parserPath+"$"+testRuleName+"_return");
+                		Class<?> _return = Class.forName(parserPath+"$"+testRuleName+"_return");
                 		Method[] methods = _return.getDeclaredMethods();
                 		for(Method method : methods) {
 			                if ( method.getName().equals("getTree") ) {
@@ -240,13 +226,13 @@
 
 			this.stdout = "";
 			this.stderr = "";
-			
+
 			/** Invalid input */
             if ( tokens.index()!=tokens.size()-1 ) {
             	//throw new InvalidInputException();
             	this.stderr += "Stopped parsing at token index "+tokens.index()+": ";
             }
-            
+
 			// retVal could be actual return object from rule, stderr or stdout
             this.stdout += out.toString();
             this.stderr += err.toString();
@@ -267,16 +253,16 @@
 			}
 		}
         catch (ClassNotFoundException e) {
-			e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
 		}
         catch (SecurityException e) {
-			e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
 		}
         catch (NoSuchMethodException e) {
-			e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
 		}
         catch (IllegalAccessException e) {
-			e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException(e);
 		}
         catch (InvocationTargetException e) {
             this.stdout = out.toString();
@@ -297,7 +283,7 @@
         }
 		return this.stdout;
 	}
-	
+
 	// Invoke target parser.rule
 	public Object execTreeParser(String testTreeRuleName, String testRuleName, String testInput, boolean isFile) throws Exception {
 		CharStream input;
@@ -314,37 +300,32 @@
 		else {
 			input = new ANTLRStringStream(testInput);
 		}
-		Class lexer = null;
-		Class parser = null;
-		Class treeParser = null;
+		Class<? extends Lexer> lexer;
+		Class<? extends Parser> parser;
+		Class<? extends TreeParser> treeParser;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
 		try {
 			/** Use Reflection to create instances of lexer and parser */
-        	lexer = Class.forName(lexerPath);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);        
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args   
-            Object lexObj = lexConstructor.newInstance(lexArgs);				// makes new instance of lexer    
-            
-            CommonTokenStream tokens = new CommonTokenStream((Lexer) lexObj);
-            
-            parser = Class.forName(parserPath);
-            Class[] parArgTypes = new Class[]{TokenStream.class};				// assign type to parser's args
-            Constructor parConstructor = parser.getConstructor(parArgTypes);
-            Object[] parArgs = new Object[]{tokens};							// assign value to parser's args  
-            Object parObj = parConstructor.newInstance(parArgs);				// makes new instance of parser      
-            
+        	lexer = Class.forName(lexerPath).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
+
+            CommonTokenStream tokens = new CommonTokenStream(lexObj);
+
+            parser = Class.forName(parserPath).asSubclass(Parser.class);
+            Constructor<? extends Parser> parConstructor = parser.getConstructor(TokenStream.class);
+            Parser parObj = parConstructor.newInstance(tokens);				// makes new instance of parser
+
             // set up customized tree adaptor if necessary
-            TreeAdaptor customTreeAdaptor = null; 
+            TreeAdaptor customTreeAdaptor = null;
             if ( treeAdaptorPath!=null ) {
-            	parArgTypes = new Class[]{TreeAdaptor.class};
-            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", parArgTypes);
-            	Class _treeAdaptor = Class.forName(treeAdaptorPath);
-            	customTreeAdaptor = (TreeAdaptor) _treeAdaptor.newInstance();
+            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", TreeAdaptor.class);
+            	Class<? extends TreeAdaptor> _treeAdaptor = Class.forName(treeAdaptorPath).asSubclass(TreeAdaptor.class);
+            	customTreeAdaptor = _treeAdaptor.newInstance();
             	_setTreeAdaptor.invoke(parObj, customTreeAdaptor);
             }
-            
+
             Method ruleName = parser.getMethod(testRuleName);
 
             /** Start of I/O Redirecting */
@@ -358,8 +339,8 @@
 
             /** Invoke grammar rule, and get the return value */
             Object ruleReturn = ruleName.invoke(parObj);
-            
-            Class _return = Class.forName(parserPath+"$"+testRuleName+"_return");            	
+
+            Class<?> _return = Class.forName(parserPath+"$"+testRuleName+"_return");
         	Method returnName = _return.getMethod("getTree");
         	CommonTree tree = (CommonTree) returnName.invoke(ruleReturn);
 
@@ -374,22 +355,20 @@
         	// AST nodes have payload that point into token stream
         	nodes.setTokenStream(tokens);
         	// Create a tree walker attached to the nodes stream
-        	treeParser = Class.forName(treeParserPath);
-            Class[] treeParArgTypes = new Class[]{TreeNodeStream.class};		// assign type to tree parser's args
-            Constructor treeParConstructor = treeParser.getConstructor(treeParArgTypes);
-            Object[] treeParArgs = new Object[]{nodes};							// assign value to tree parser's args  
-            Object treeParObj = treeParConstructor.newInstance(treeParArgs);	// makes new instance of tree parser      
+        	treeParser = Class.forName(treeParserPath).asSubclass(TreeParser.class);
+            Constructor<? extends TreeParser> treeParConstructor = treeParser.getConstructor(TreeNodeStream.class);
+            TreeParser treeParObj = treeParConstructor.newInstance(nodes);	// makes new instance of tree parser
         	// Invoke the tree rule, and store the return value if there is
             Method treeRuleName = treeParser.getMethod(testTreeRuleName);
             Object treeRuleReturn = treeRuleName.invoke(treeParObj);
-            
+
             String astString = null;
             String stString = null;
             /** If tree rule has return value, determine if it contains an AST or a ST */
             if ( treeRuleReturn!=null ) {
                 if ( treeRuleReturn.getClass().toString().indexOf(testTreeRuleName+"_return")>0 ) {
                 	try {	// NullPointerException may happen here...
-                		Class _treeReturn = Class.forName(treeParserPath+"$"+testTreeRuleName+"_return");
+                		Class<?> _treeReturn = Class.forName(treeParserPath+"$"+testTreeRuleName+"_return");
                 		Method[] methods = _treeReturn.getDeclaredMethods();
 			            for(Method method : methods) {
 			                if ( method.getName().equals("getTree") ) {
@@ -412,12 +391,12 @@
 
 			this.stdout = null;
 			this.stderr = null;
-			
+
 			/** Invalid input */
             if ( tokens.index()!=tokens.size()-1 ) {
             	throw new InvalidInputException();
             }
-			
+
 			// retVal could be actual return object from rule, stderr or stdout
 			if ( err.toString().length()>0 ) {
 				this.stderr = err.toString();
@@ -439,13 +418,13 @@
 				return null;
 			}
 		} catch (ClassNotFoundException e) {
-			e.printStackTrace(); System.exit(1);
+			handleUnexpectedException(e);
 		} catch (SecurityException e) {
-			e.printStackTrace(); System.exit(1);
+			handleUnexpectedException(e);
 		} catch (NoSuchMethodException e) {
-			e.printStackTrace(); System.exit(1);
+			handleUnexpectedException(e);
 		} catch (IllegalAccessException e) {
-			e.printStackTrace(); System.exit(1);
+			handleUnexpectedException(e);
 		} catch (InvocationTargetException e) {
 			if ( e.getCause()!=null ) this.stderr = e.getCause().toString();
 			else this.stderr = e.toString();
@@ -462,11 +441,13 @@
         }
 		return stdout;
 	}
-	
+
 	// Modify the return value if the expected token type is OK or FAIL
-	public Object examineExecResult(int tokenType, Object retVal) {	
+	public Object examineExecResult(int tokenType, Object retVal) {
+		System.out.println("expect "+(tokenType==gUnitParser.OK?"OK":"FAIL")+
+						   "stderr=="+stderr);
 		if ( tokenType==gUnitParser.OK ) {	// expected Token: OK
-			if ( this.stderr==null ) {
+			if ( this.stderr==null || this.stderr.length()==0 ) {
 				return "OK";
 			}
 			else {
@@ -474,7 +455,7 @@
 			}
 		}
 		else if ( tokenType==gUnitParser.FAIL ) {	// expected Token: FAIL
-			if ( this.stderr!=null ) {
+			if ( this.stderr!=null && this.stderr.length()>0 ) {
 				return "FAIL";
 			}
 			else {
@@ -483,7 +464,12 @@
 		}
 		else {	// return the same object for the other token types
 			return retVal;
-		}		
+		}
 	}
-	
+
+	protected void handleUnexpectedException(Exception e) {
+		e.printStackTrace();
+		System.exit(1);
+	}
+
 }
diff --git a/gunit/src/main/java/org/antlr/gunit/gUnitExecutor.java b/gunit/src/main/java/org/antlr/gunit/gUnitExecutor.java
index 8498c65..ab759c8 100644
--- a/gunit/src/main/java/org/antlr/gunit/gUnitExecutor.java
+++ b/gunit/src/main/java/org/antlr/gunit/gUnitExecutor.java
@@ -47,6 +47,8 @@
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
+import org.antlr.runtime.tree.TreeParser;
 
 public class gUnitExecutor implements ITestSuite {
 	public GrammarInfo grammarInfo;
@@ -103,7 +105,7 @@
 		return grammarClassLoader;
 	}
 
-	protected final Class classForName(String name) throws ClassNotFoundException {
+	protected final Class<?> classForName(String name) throws ClassNotFoundException {
 		return getGrammarClassLoader().loadClass( name );
 	}
 
@@ -146,8 +148,7 @@
 			}
 		}
 		catch (Exception e) {
-            e.printStackTrace();
-            System.exit(1);
+			handleUnexpectedException(e);
         }
 		return testResultST.toString();
 	}
@@ -173,11 +174,12 @@
 			String rule = ts.getRuleName();
 			String lexicalRule = ts.getLexicalRuleName();
 			String treeRule = ts.getTreeRuleName();
-			for ( gUnitTestInput input: ts.testSuites.keySet() ) {	// each rule may contain multiple tests
+			for ( Map.Entry<gUnitTestInput, AbstractTest> entry : ts.testSuites.entrySet() ) {	// each rule may contain multiple tests
+				gUnitTestInput input = entry.getKey();
 				numOfTest++;
 				// Run parser, and get the return value or stdout or stderr if there is
 				gUnitTestResult result = null;
-				AbstractTest test = ts.testSuites.get(input);
+				AbstractTest test = entry.getValue();
 				try {
 					// TODO: create a -debug option to turn on logging, which shows progress of running tests
 					//System.out.print(numOfTest + ". Running rule: " + rule + "; input: '" + input.testInput + "'");
@@ -186,7 +188,7 @@
 					//System.out.println("; Expecting " + test.getExpected() + "; Success?: " + test.getExpected().equals(test.getResult(result)));
 				} catch ( InvalidInputException e) {
 					numOfInvalidInput++;
-                    test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line);
+					test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line, input.input);
 					test.setActual(input.input);
 					invalids.add(test);
 					continue;
@@ -198,7 +200,7 @@
 
 				if (actual == null) {
 					numOfFailure++;
-                    test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line);
+					test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line, input.input);
 					test.setActual("null");
 					failures.add(test);
 					onFail(test);
@@ -211,14 +213,14 @@
 				// TODO: something with ACTIONS - at least create action test type and throw exception.
 				else if ( ts.testSuites.get(input).getType()==gUnitParser.ACTION ) {	// expected Token: ACTION
 					numOfFailure++;
-                    test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line);
+					test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line, input.input);
 					test.setActual("\t"+"{ACTION} is not supported in the grammarInfo yet...");
 					failures.add(test);
 					onFail(test);
 				}
 				else {
 					numOfFailure++;
-                    test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line);
+					test.setHeader(rule, lexicalRule, treeRule, numOfTest, input.line, input.input);
 					failures.add(test);
 					onFail(test);
 				}
@@ -229,7 +231,7 @@
 	// TODO: throw proper exceptions
 	protected gUnitTestResult runLexer(String lexerName, String testRuleName, gUnitTestInput testInput) throws Exception {
 		CharStream input;
-		Class lexer = null;
+		Class<? extends Lexer> lexer;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
 		try {
@@ -237,13 +239,11 @@
 			input = getANTLRInputStream(testInput);
 
             /** Use Reflection to create instances of lexer and parser */
-        	lexer = classForName(lexerName);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args
-            Object lexObj = lexConstructor.newInstance(lexArgs);				// makes new instance of lexer
+        	lexer = classForName(lexerName).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
 
-            Method ruleName = lexer.getMethod("m"+testRuleName, new Class[0]);
+            Method ruleName = lexer.getMethod("m"+testRuleName);
 
             /** Start of I/O Redirecting */
             ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -255,9 +255,9 @@
             /** End of redirecting */
 
             /** Invoke lexer rule, and get the current index in CharStream */
-            ruleName.invoke(lexObj, new Object[0]);
-            Method ruleName2 = lexer.getMethod("getCharIndex", new Class[0]);
-            int currentIndex = (Integer) ruleName2.invoke(lexObj, new Object[0]);
+            ruleName.invoke(lexObj);
+            Method ruleName2 = lexer.getMethod("getCharIndex");
+            int currentIndex = (Integer) ruleName2.invoke(lexObj);
             if ( currentIndex!=input.size() ) {
             	ps2.print("extra text found, '"+input.substring(currentIndex, input.size()-1)+"'");
             }
@@ -275,17 +275,17 @@
 		} catch (IOException e) {
 			return getTestExceptionResult(e);
         } catch (ClassNotFoundException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (SecurityException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (NoSuchMethodException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalArgumentException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InstantiationException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalAccessException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InvocationTargetException e) {	// This exception could be caused from ANTLR Runtime Exception, e.g. MismatchedTokenException
         	return getTestExceptionResult(e);
         } finally {
@@ -305,8 +305,8 @@
 	// TODO: throw proper exceptions
 	protected gUnitTestResult runParser(String parserName, String lexerName, String testRuleName, gUnitTestInput testInput) throws Exception {
 		CharStream input;
-		Class lexer = null;
-		Class parser = null;
+		Class<? extends Lexer> lexer;
+		Class<? extends Parser> parser;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
 		try {
@@ -314,25 +314,20 @@
 			input = getANTLRInputStream(testInput);
 
             /** Use Reflection to create instances of lexer and parser */
-        	lexer = classForName(lexerName);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args
-            Object lexObj = lexConstructor.newInstance(lexArgs);				// makes new instance of lexer
+        	lexer = classForName(lexerName).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
 
-            CommonTokenStream tokens = new CommonTokenStream((Lexer) lexObj);
+            CommonTokenStream tokens = new CommonTokenStream(lexObj);
 
-            parser = classForName(parserName);
-            Class[] parArgTypes = new Class[]{TokenStream.class};				// assign type to parser's args
-            Constructor parConstructor = parser.getConstructor(parArgTypes);
-            Object[] parArgs = new Object[]{tokens};							// assign value to parser's args
-            Object parObj = parConstructor.newInstance(parArgs);				// makes new instance of parser
+            parser = classForName(parserName).asSubclass(Parser.class);
+            Constructor<? extends Parser> parConstructor = parser.getConstructor(TokenStream.class);
+            Parser parObj = parConstructor.newInstance(tokens);				// makes new instance of parser
 
             // set up customized tree adaptor if necessary
             if ( grammarInfo.getAdaptor()!=null ) {
-            	parArgTypes = new Class[]{TreeAdaptor.class};
-            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", parArgTypes);
-            	Class _treeAdaptor = classForName(grammarInfo.getAdaptor());
+            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", TreeAdaptor.class);
+            	Class<? extends TreeAdaptor> _treeAdaptor = classForName(grammarInfo.getAdaptor()).asSubclass(TreeAdaptor.class);
             	_setTreeAdaptor.invoke(parObj, _treeAdaptor.newInstance());
             }
 
@@ -355,7 +350,7 @@
             if ( ruleReturn!=null ) {
                 if ( ruleReturn.getClass().toString().indexOf(testRuleName+"_return")>0 ) {
                 	try {	// NullPointerException may happen here...
-                		Class _return = classForName(parserName+"$"+testRuleName+"_return");
+                		Class<?> _return = classForName(parserName+"$"+testRuleName+"_return");
                 		Method[] methods = _return.getDeclaredMethods();
                 		for(Method method : methods) {
 			                if ( method.getName().equals("getTree") ) {
@@ -376,11 +371,7 @@
                 }
             }
 
-            /** Invalid input */
-            if ( tokens.index()!=tokens.size()-1 ) {
-            	//throw new InvalidInputException();
-            	ps2.print("Invalid input");
-            }
+            checkForValidInput(tokens, ps2);
 
 			if ( err.toString().length()>0 ) {
 				gUnitTestResult testResult = new gUnitTestResult(false, err.toString());
@@ -407,17 +398,17 @@
 		} catch (IOException e) {
 			return getTestExceptionResult(e);
 		} catch (ClassNotFoundException e) {
-        	e.printStackTrace(); System.exit(1);
+			handleUnexpectedException( e );
         } catch (SecurityException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (NoSuchMethodException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalArgumentException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InstantiationException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalAccessException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InvocationTargetException e) {	// This exception could be caused from ANTLR Runtime Exception, e.g. MismatchedTokenException
         	return getTestExceptionResult(e);
         } finally {
@@ -437,9 +428,9 @@
 	protected gUnitTestResult runTreeParser(String parserName, String lexerName, String testRuleName, String testTreeRuleName, gUnitTestInput testInput) throws Exception {
 		CharStream input;
 		String treeParserPath;
-		Class lexer = null;
-		Class parser = null;
-		Class treeParser = null;
+		Class<? extends Lexer> lexer;
+		Class<? extends Parser> parser;
+		Class<? extends TreeParser> treeParser;
 		PrintStream ps = null;		// for redirecting stdout later
 		PrintStream ps2 = null;		// for redirecting stderr later
 		try {
@@ -455,27 +446,22 @@
 			}
 
             /** Use Reflection to create instances of lexer and parser */
-        	lexer = classForName(lexerName);
-            Class[] lexArgTypes = new Class[]{CharStream.class};				// assign type to lexer's args
-            Constructor lexConstructor = lexer.getConstructor(lexArgTypes);
-            Object[] lexArgs = new Object[]{input};								// assign value to lexer's args
-            Object lexObj = lexConstructor.newInstance(lexArgs);				// makes new instance of lexer
+        	lexer = classForName(lexerName).asSubclass(Lexer.class);
+            Constructor<? extends Lexer> lexConstructor = lexer.getConstructor(CharStream.class);
+            Lexer lexObj = lexConstructor.newInstance(input);				// makes new instance of lexer
 
-            CommonTokenStream tokens = new CommonTokenStream((Lexer) lexObj);
+            CommonTokenStream tokens = new CommonTokenStream(lexObj);
 
-            parser = classForName(parserName);
-            Class[] parArgTypes = new Class[]{TokenStream.class};				// assign type to parser's args
-            Constructor parConstructor = parser.getConstructor(parArgTypes);
-            Object[] parArgs = new Object[]{tokens};							// assign value to parser's args
-            Object parObj = parConstructor.newInstance(parArgs);				// makes new instance of parser
+            parser = classForName(parserName).asSubclass(Parser.class);
+            Constructor<? extends Parser> parConstructor = parser.getConstructor(TokenStream.class);
+            Parser parObj = parConstructor.newInstance(tokens);				// makes new instance of parser
 
             // set up customized tree adaptor if necessary
             TreeAdaptor customTreeAdaptor = null;
             if ( grammarInfo.getAdaptor()!=null ) {
-            	parArgTypes = new Class[]{TreeAdaptor.class};
-            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", parArgTypes);
-            	Class _treeAdaptor = classForName(grammarInfo.getAdaptor());
-            	customTreeAdaptor = (TreeAdaptor) _treeAdaptor.newInstance();
+            	Method _setTreeAdaptor = parser.getMethod("setTreeAdaptor", TreeAdaptor.class);
+            	Class<? extends TreeAdaptor> _treeAdaptor = classForName(grammarInfo.getAdaptor()).asSubclass(TreeAdaptor.class);
+            	customTreeAdaptor = _treeAdaptor.newInstance();
             	_setTreeAdaptor.invoke(parObj, customTreeAdaptor);
             }
 
@@ -493,7 +479,7 @@
             /** Invoke grammar rule, and get the return value */
             Object ruleReturn = ruleName.invoke(parObj);
 
-            Class _return = classForName(parserName+"$"+testRuleName+"_return");
+            Class<?> _return = classForName(parserName+"$"+testRuleName+"_return");
         	Method returnName = _return.getMethod("getTree");
         	CommonTree tree = (CommonTree) returnName.invoke(ruleReturn);
 
@@ -508,11 +494,9 @@
         	// AST nodes have payload that point into token stream
         	nodes.setTokenStream(tokens);
         	// Create a tree walker attached to the nodes stream
-        	treeParser = classForName(treeParserPath);
-            Class[] treeParArgTypes = new Class[]{TreeNodeStream.class};		// assign type to tree parser's args
-            Constructor treeParConstructor = treeParser.getConstructor(treeParArgTypes);
-            Object[] treeParArgs = new Object[]{nodes};							// assign value to tree parser's args
-            Object treeParObj = treeParConstructor.newInstance(treeParArgs);	// makes new instance of tree parser
+        	treeParser = classForName(treeParserPath).asSubclass(TreeParser.class);
+            Constructor<? extends TreeParser> treeParConstructor = treeParser.getConstructor(TreeNodeStream.class);
+            TreeParser treeParObj = treeParConstructor.newInstance(nodes);	// makes new instance of tree parser
         	// Invoke the tree rule, and store the return value if there is
             Method treeRuleName = treeParser.getMethod(testTreeRuleName);
             Object treeRuleReturn = treeRuleName.invoke(treeParObj);
@@ -523,7 +507,7 @@
             if ( treeRuleReturn!=null ) {
                 if ( treeRuleReturn.getClass().toString().indexOf(testTreeRuleName+"_return")>0 ) {
                 	try {	// NullPointerException may happen here...
-                		Class _treeReturn = classForName(treeParserPath+"$"+testTreeRuleName+"_return");
+                		Class<?> _treeReturn = classForName(treeParserPath+"$"+testTreeRuleName+"_return");
                 		Method[] methods = _treeReturn.getDeclaredMethods();
 			            for(Method method : methods) {
 			                if ( method.getName().equals("getTree") ) {
@@ -544,11 +528,7 @@
                 }
             }
 
-            /** Invalid input */
-            if ( tokens.index()!=tokens.size()-1 ) {
-            	//throw new InvalidInputException();
-            	ps2.print("Invalid input");
-            }
+			checkForValidInput( tokens, ps2 );
 
 			if ( err.toString().length()>0 ) {
 				gUnitTestResult testResult = new gUnitTestResult(false, err.toString());
@@ -576,17 +556,17 @@
 		} catch (IOException e) {
 			return getTestExceptionResult(e);
 		} catch (ClassNotFoundException e) {
-        	e.printStackTrace(); System.exit(1);
+			handleUnexpectedException( e );
         } catch (SecurityException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (NoSuchMethodException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalArgumentException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InstantiationException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (IllegalAccessException e) {
-        	e.printStackTrace(); System.exit(1);
+        	handleUnexpectedException( e );
         } catch (InvocationTargetException e) {	// note: This exception could be caused from ANTLR Runtime Exception...
         	return getTestExceptionResult(e);
         } finally {
@@ -641,6 +621,23 @@
     	return testResult;
 	}
 
+	/**
+	 * Verify the input has been properly consumed
+	 */
+	protected void checkForValidInput(CommonTokenStream tokens, PrintStream ps2) {
+		if ( tokens.index() != tokens.size() - 1 ) {
+			//At this point we need to check for redundant EOF tokens
+			//which might have been added by the Parser:
+			List<? extends Token> endingTokens = tokens.getTokens(tokens.index(), tokens.size() -1);
+			for (Token endToken : endingTokens) {
+				if (! "<EOF>".equals(endToken.getText())) {
+					//writing to ps2 will mark the test as failed:
+					ps2.print( "Invalid input" );
+					return;
+				}
+			}
+		}
+	}
 
     public void onPass(ITestCase passTest) {
 
@@ -650,4 +647,9 @@
 
     }
 
+	protected void handleUnexpectedException(Exception e) {
+		e.printStackTrace();
+		System.exit(1);
+	}
+
 }
diff --git a/gunit/src/main/java/org/antlr/gunit/swingui/TestCaseEditController.java b/gunit/src/main/java/org/antlr/gunit/swingui/TestCaseEditController.java
index 30cf0ae..2f15229 100644
--- a/gunit/src/main/java/org/antlr/gunit/swingui/TestCaseEditController.java
+++ b/gunit/src/main/java/org/antlr/gunit/swingui/TestCaseEditController.java
@@ -96,9 +96,9 @@
 
     /* END OF MODEL*/
 
-    private static final HashMap<Class, String> TypeNameTable;
+    private static final HashMap<Class<?>, String> TypeNameTable;
     static {
-        TypeNameTable = new HashMap<Class, String> ();
+        TypeNameTable = new HashMap<Class<?>, String> ();
         TypeNameTable.put(TestCaseInputString.class, IN_TYPE_STRING);
         TypeNameTable.put(TestCaseInputMultiString.class, IN_TYPE_MULTI);
         TypeNameTable.put(TestCaseInputFile.class, IN_TYPE_FILE);
diff --git a/gunit/src/main/java/org/antlr/gunit/swingui/model/TestSuite.java b/gunit/src/main/java/org/antlr/gunit/swingui/model/TestSuite.java
index 06e5227..1264f30 100644
--- a/gunit/src/main/java/org/antlr/gunit/swingui/model/TestSuite.java
+++ b/gunit/src/main/java/org/antlr/gunit/swingui/model/TestSuite.java
@@ -95,6 +95,6 @@
     }
     
     // only for stringtemplate use
-    public List getRulesForStringTemplate() {return rules;}
+    public List<Rule> getRulesForStringTemplate() {return rules;}
     
 }
diff --git a/gunit/src/main/java/org/antlr/gunit/swingui/runner/ParserLoader.java b/gunit/src/main/java/org/antlr/gunit/swingui/runner/ParserLoader.java
index 23f5aa0..dcad501 100644
--- a/gunit/src/main/java/org/antlr/gunit/swingui/runner/ParserLoader.java
+++ b/gunit/src/main/java/org/antlr/gunit/swingui/runner/ParserLoader.java
@@ -31,12 +31,12 @@
 import java.util.HashMap;
 
 /**
- * Class loader for parser & lexer generated by antlr.
+ * Class loader for parser &amp; lexer generated by antlr.
  * @author Shaoting
  */
 public class ParserLoader extends ClassLoader {
 
-    private HashMap<String, Class> classList;
+    private HashMap<String, Class<?>> classList;
     private String grammar;
 
     /**
@@ -51,7 +51,7 @@
         // load all the class files in the "classDir" related to the grammarName
         File dir = new File(classDir);
         if(dir.isDirectory()) {
-            classList = new HashMap<String, Class>();
+            classList = new HashMap<String, Class<?>>();
             grammar = grammarName;
             File[] files = dir.listFiles(new ClassFilenameFilter(grammarName));
             for(File f : files) {
@@ -63,7 +63,7 @@
                 in.close();
 
                 // define class
-                final Class newClass = defineClass(null, classData, 0, classData.length);
+                final Class<?> newClass = defineClass(null, classData, 0, classData.length);
                 assert(newClass != null);
                 resolveClass(newClass);
 
@@ -86,7 +86,7 @@
 
 
     @Override
-    public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
+    public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
         //System.out.print("loading: " + name);
         if(name.startsWith(grammar)) {
             if(classList.containsKey(name)) {
@@ -98,7 +98,7 @@
             }
             
         } else {
-            final Class c = findSystemClass(name);
+            final Class<?> c = findSystemClass(name);
             //System.out.println(" .... system found " + c.getName());
             return c;
         }
diff --git a/lib/antlr-3.4-complete.jar b/lib/antlr-3.4-complete.jar
deleted file mode 100644
index 9c985c7..0000000
--- a/lib/antlr-3.4-complete.jar
+++ /dev/null
Binary files differ
diff --git a/patches/fix_infinite_recursion.diff b/patches/fix_infinite_recursion.diff
new file mode 100644
index 0000000..06d8815
--- /dev/null
+++ b/patches/fix_infinite_recursion.diff
@@ -0,0 +1,24 @@
+From 12f69f5bb0e10f608b1899bab67b1813e0fdaf14 Mon Sep 17 00:00:00 2001
+From: Andreas Gampe <agampe@google.com>
+Date: Tue, 20 Feb 2018 09:51:42 -0800
+Subject: [PATCH] Antlr: Fix infinite recursion
+
+Bug: 73645371
+Test: m javac-check RUN_ERROR_PRONE=true
+Change-Id: Ie8702ad59aab1af7e23038fbffd5bd34902f1f7c
+---
+
+Index: antlr/runtime/Java/src/main/java/org/antlr/runtime/debug/DebugTreeAdaptor.java
+===================================================================
+--- antlr.orig/runtime/Java/src/main/java/org/antlr/runtime/debug/DebugTreeAdaptor.java
++++ antlr/runtime/Java/src/main/java/org/antlr/runtime/debug/DebugTreeAdaptor.java
+@@ -227,7 +227,7 @@ public class DebugTreeAdaptor implements
+ 
+ 	@Override
+ 	public Object deleteChild(Object t, int i) {
+-		return deleteChild(t, i);
++		return adaptor.deleteChild(t, i);
+ 	}
+ 
+ 	@Override
+
diff --git a/pom.xml b/pom.xml
index c2f9cc7..bcec4b5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,32 +1,25 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
-
-    <!--
-        The ANTLR Maven artifacts are now released via the Sonotype OSS
-        repository, which means that they are synced to Maven central 
-        within a few minutes of hitting the release repo for Sonotype.
-        To enable this, we inherit from the Sonotype provided parent
-        pom. However, we must also configure our .m2/settings.xml to include
-        the snapshot and staging server and the sonotype password. This 
-        means that only ANTLR developers can released the artifacts, but
-        anyone can build locally.
-      -->
     <parent>
         <groupId>org.sonatype.oss</groupId>
         <artifactId>oss-parent</artifactId>
-        <version>7</version>
-    </parent>    
-    
+        <version>9</version>
+    </parent>
+
     <modelVersion>4.0.0</modelVersion>
     <groupId>org.antlr</groupId>
     <artifactId>antlr-master</artifactId>
     <packaging>pom</packaging>
-    <version>3.4</version>
-    <name>ANTLR Master build control POM 3.4</name>
-    <url>http://maven.apache.org</url>
-
-
+    <version>3.5.2</version>
+    <name>ANTLR 3 Master build control POM</name>
+    <description>Master build POM for ANTLR 3</description>
+    <url>http://antlr.org</url>
+    <inceptionYear>1992</inceptionYear>
+    <organization>
+        <name>ANTLR</name>
+        <url>http://www.antlr.org</url>
+    </organization>
 
   <!--
     What version of ANTLR are we building? This sets the
@@ -40,171 +33,59 @@
      This is the master pom for building the ANTLR
      toolset and runtime (Java) at the specific level
      defined above. Hence we specify here the modules that
-     this pom will build when we build this pom in certain profiles.
+     this pom will build when we build this pom
     -->
 
+    <modules>
+        <module>runtime/Java</module>
+        <module>tool</module>
+        <module>antlr3-maven-plugin</module>
+        <module>gunit</module>
+        <module>gunit-maven-plugin</module>
+        <module>antlr3-maven-archetype</module>
+        <module>antlr-complete</module>
+    </modules>
+
   <!--
     Make sure that the build is not platform dependent (I.E show that
     all the files in the source tree are in UTF-8 format.
     -->
     <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <java5.home>${env.JAVA5_HOME}</java5.home>
+        <java6.home>${env.JAVA6_HOME}</java6.home>
+        <bootclasspath.java5>${java5.home}/lib/rt.jar</bootclasspath.java5>
+        <bootclasspath.java6>${java6.home}/lib/rt.jar</bootclasspath.java6>
+        <bootclasspath.compile>${bootclasspath.java5}</bootclasspath.compile>
+        <bootclasspath.testCompile>${bootclasspath.java6}</bootclasspath.testCompile>
     </properties>
 
-        <profiles>
-            <profile>
-                <id>standard</id>
-                <activation>
-                    <activeByDefault>true</activeByDefault>
-                </activation>
-                <modules>
-                    <module>runtime/Java</module>
-                    <module>tool</module>
-                    <module>antlr3-maven-plugin</module>
-                    <module>gunit</module>
-                    <module>gunit-maven-plugin</module>
-                    <module>antlr3-maven-archetype</module>
-                </modules>
-            </profile>
+    <licenses>
+        <license>
+            <name>BSD licence</name>
+            <url>http://antlr.org/license.html</url>
+            <distribution>repo</distribution>
+        </license>
+    </licenses>
 
-            <!--
-                Activate this profile to build ONLY the Uber jar, which is the
-                ANTLR tool and its dependencies (no plugins etc).
-                
-                mvn -Duber -DskipTests package assembly:assembly
-                
-              -->
-            <profile>
-                <id>uber</id>
-                <activation>
-                    <property>
-                        <name>uber</name>
-                        <value>true</value>
-                    </property>
-                </activation>
-                <modules>
-                    <module>runtime/Java</module>
-                    <module>tool</module>
-                </modules>
-                <build>
-                    <plugins>
-                        <plugin>
+    <issueManagement>
+        <system>GitHub Issues</system>
+        <url>https://github.com/antlr/antlr3/issues</url>
+    </issueManagement>
 
-                        <!--
+    <mailingLists>
+        <mailingList>
+            <name>antlr-discussion</name>
+            <archive>https://groups.google.com/forum/?fromgroups#!forum/antlr-discussion</archive>
+        </mailingList>
+    </mailingLists>
 
-                            Build an uber-jar for the ANTLR Tool that is packaged with all the other dependencies,
-                            such as the antlr-runtime and stringtemplate etc. This will be useful
-                            for developers, who then do not need to download anything else or
-                            remember that they need stringtemplate.jar in their CLASSPATH and so
-                            on.
-
-                            This does not preclude any of the module generated jars from
-                            being used on their own of course.
-
-                            Here, we also build a master source jar as I was unable to pursuade
-                            this plugin to use multiple configurations and not have the thing
-                            screw up because of multiple modules :-(
-
-                          -->
-
-                            <artifactId>maven-assembly-plugin</artifactId>
-                            <version>2.2.1</version>
-                            <!--
-                                Do not make the child modules build an assembly
-                              -->
-                            <inherited>false</inherited>
-
-                            <configuration>
-                                <descriptors>
-                                    <descriptor>antlrjar.xml</descriptor>
-                                    <descriptor>antlrsources.xml</descriptor>
-                                </descriptors>
-                                    <!--
-
-                                        Specify that we want the resulting jar to be executable
-                                        via java -jar, which we do by modifying the manifest
-                                        of course.
-                                      -->
-                                <archive>
-                                    <manifest>
-                                        <mainClass>org.antlr.Tool</mainClass>
-                                    </manifest>
-                                </archive>
-                            </configuration>
-
-                        </plugin>
-                    </plugins>
-                </build>
-            </profile>
-            
-            <profile>
-                <id>release-sign-artifacts</id>
-                <activation>
-                    <property>
-                        <name>deploy</name>
-                        <value>true</value>
-                    </property>
-                </activation>
-                <modules>
-                    <module>runtime/Java</module>
-                    <module>tool</module>
-                    <module>antlr3-maven-plugin</module>
-                    <module>gunit</module>
-                    <module>gunit-maven-plugin</module>
-                    <module>antlr3-maven-archetype</module>
-                </modules>
-                <build>
-                    <plugins>
-                        
-                        <plugin>
-                            <groupId>org.apache.maven.plugins</groupId>
-                            <artifactId>maven-gpg-plugin</artifactId>
-                            <version>1.3</version>
-                            <executions>
-                                <execution>
-                                    <id>sign-artifacts</id>
-                                    <phase>verify</phase>
-                                    <goals>
-                                       <goal>sign</goal>
-                                    </goals>
-                                </execution>
-                            </executions>
-                        </plugin>
-                        
-                        <plugin>
-                            <groupId>org.apache.maven.plugins</groupId>
-                            <artifactId>maven-javadoc-plugin</artifactId>
-                            <version>2.8</version>
-                            <executions>
-                                <execution>
-                                    <id>attach-javadocs</id>
-                                    <goals>
-                                        <goal>jar</goal>
-                                    </goals>
-                                </execution>
-                            </executions>
-                        </plugin>
-                        
-                        <plugin>
-                            <groupId>org.apache.maven.plugins</groupId>
-                            <artifactId>maven-source-plugin</artifactId>
-                            <version>2.1.2</version>
-                            <executions>
-                                <execution>
-                                    <id>attach-sources</id>
-                                    <goals>
-                                       <goal>jar</goal>
-                                    </goals>
-                                </execution>
-                            </executions>
-                        </plugin>
-                        
-                    </plugins>
-                </build>
-            </profile>
-            
-    </profiles>
-
+    <scm>
+        <url>https://github.com/antlr/antlr3/tree/master</url>
+        <connection>scm:git:git://github.com/antlr/antlr3.git</connection>
+        <developerConnection>scm:git:git@github.com:antlr/antlr3.git</developerConnection>
+      <tag>3.5.2</tag>
+  </scm>
   <!--
 
     Tell Maven which other artifacts we need in order to
@@ -220,15 +101,80 @@
             <dependency>
                 <groupId>junit</groupId>
                 <artifactId>junit</artifactId>
-                <version>4.8.2</version>
+                <version>4.10</version>
                 <scope>test</scope>
             </dependency>
 
+            <dependency>
+                <groupId>antlr</groupId>
+                <artifactId>antlr</artifactId>
+                <version>2.7.7</version>
+                <scope>compile</scope>
+            </dependency>
+
+            <dependency>
+              <groupId>org.antlr</groupId>
+              <artifactId>stringtemplate</artifactId>
+              <version>3.2.1</version>
+              <scope>compile</scope>
+            </dependency>
+
+            <dependency>
+                <groupId>org.antlr</groupId>
+                <artifactId>ST4</artifactId>
+                <version>4.0.8</version>
+                <scope>compile</scope>
+            </dependency>
 
         </dependencies>
 
     </dependencyManagement>
 
+    <profiles>
+        <profile>
+            <id>sonatype-oss-release</id>
+            <modules>
+                <module>antlr-complete</module>
+            </modules>
+            <build>
+                <plugins>
+                    <plugin>
+                        <groupId>org.apache.maven.plugins</groupId>
+                        <artifactId>maven-compiler-plugin</artifactId>
+                        <executions>
+                            <execution>
+                                <id>default-compile</id>
+                                <configuration>
+                                    <source>1.5</source>
+                                    <target>1.5</target>
+                                    <compilerArgs>
+                                        <arg>-Xlint</arg>
+                                        <arg>-Xlint:-serial</arg>
+                                        <arg>-bootclasspath</arg>
+                                        <arg>${bootclasspath.compile}</arg>
+                                    </compilerArgs>
+                                </configuration>
+                            </execution>
+                            <execution>
+                                <id>default-testCompile</id>
+                                <configuration>
+                                    <source>1.6</source>
+                                    <target>1.6</target>
+                                    <compilerArgs>
+                                        <arg>-Xlint</arg>
+                                        <arg>-Xlint:-serial</arg>
+                                        <arg>-bootclasspath</arg>
+                                        <arg>${bootclasspath.testCompile}</arg>
+                                    </compilerArgs>
+                                </configuration>
+                            </execution>
+                        </executions>
+                    </plugin>
+                </plugins>
+            </build>
+        </profile>
+    </profiles>
+
     <build>
 
         <defaultGoal>install</defaultGoal>
@@ -258,54 +204,121 @@
         </resources>
 
         <plugins>
-
-             <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>buildnumber-maven-plugin</artifactId>
-                <version>1.0-beta-2</version>
-                <configuration>
-                  <format>{0,date,MMM dd, yyyy} {0,time,kk:mm:ss}</format>
-                  <items>
-                    <item>timestamp</item>
-                  </items>
-                </configuration>
-                <executions>
-                  <execution>
-                    <phase>validate</phase>
-                    <goals>
-                      <goal>create</goal>
-                    </goals>
-                  </execution>
-                </executions>
-             </plugin>
-
             <plugin>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <version>2.3.2</version>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-jar-plugin</artifactId>
+                <version>2.4</version>
                 <configuration>
-                    <source>1.6</source>
-                    <target>jsr14</target>
-                    <sourceDirectory>src</sourceDirectory>
+                    <archive>
+                        <manifest>
+                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
+                        </manifest>
+                    </archive>
                 </configuration>
             </plugin>
 
             <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.1</version>
+                <configuration>
+                    <sourceDirectory>src</sourceDirectory>
+                    <showWarnings>true</showWarnings>
+                    <showDeprecation>true</showDeprecation>
+                    <compilerArgs>
+                        <arg>-Xlint</arg>
+                        <arg>-Xlint:-serial</arg>
+                    </compilerArgs>
+                </configuration>
+
+                <executions>
+                    <execution>
+                        <id>default-compile</id>
+                        <configuration>
+                            <source>1.5</source>
+                            <target>1.5</target>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>default-testCompile</id>
+                        <configuration>
+                            <source>1.6</source>
+                            <target>1.6</target>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-release-plugin</artifactId>
+                <!-- override the version inherited from the parent -->
+                <version>2.5</version>
+                <configuration>
+                    <arguments>-Psonatype-oss-release ${release.arguments}</arguments>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-surefire-plugin</artifactId>
-                <version>2.9</version>
+                <!-- override the version inherited from the parent -->
+                <version>2.17</version>
             </plugin>
 
             <plugin>
                 <groupId>org.codehaus.mojo</groupId>
                 <artifactId>findbugs-maven-plugin</artifactId>
-                <version>2.3.2</version>
+                <!-- override the version inherited from the parent -->
+                <version>2.5.3</version>
                 <configuration>
                     <findbugsXmlOutput>true</findbugsXmlOutput>
-                    <findbugsXmlWithMessages>true</findbugsXmlWithMessages>
                     <xmlOutput>true</xmlOutput>
                 </configuration>
             </plugin>
-            
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-source-plugin</artifactId>
+                <!-- override the version inherited from the parent -->
+                <version>2.2.1</version>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <!-- override the version inherited from the parent -->
+                <version>2.9.1</version>
+                <configuration>
+                    <quiet>true</quiet>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-gpg-plugin</artifactId>
+                <!-- override the version inherited from the parent -->
+                <version>1.5</version>
+            </plugin>
+
         </plugins>
 
     </build>
+
+    <reporting>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <version>2.9.1</version>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-jxr-plugin</artifactId>
+                <version>2.3</version>
+            </plugin>
+        </plugins>
+    </reporting>
+
 </project>
diff --git a/post_update.sh b/post_update.sh
new file mode 100755
index 0000000..2995f11
--- /dev/null
+++ b/post_update.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+# $1 Path to the new version.
+# $2 Path to the old version.
+
+cp -a -n $2/build.gradle $1/
diff --git a/runtime/C/C.sln b/runtime/C/C.sln
index f841177..e86daeb 100644
--- a/runtime/C/C.sln
+++ b/runtime/C/C.sln
@@ -3,16 +3,6 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "C", "C.vcproj", "{0F0FE03A-78F3-4B34-9DCE-0CDFF1FB5C40}"
 EndProject
 Global
-	GlobalSection(SourceCodeControl) = preSolution
-		SccNumberOfProjects = 2
-		SccProjectName0 = Perforce\u0020Project
-		SccLocalPath0 = ..\\..
-		SccProvider0 = MSSCCI:Perforce\u0020SCM
-		SccProjectFilePathRelativizedFromConnection0 = runtime\\C\\
-		SccProjectUniqueName1 = C.vcproj
-		SccLocalPath1 = ..\\..
-		SccProjectFilePathRelativizedFromConnection1 = runtime\\C\\
-	EndGlobalSection
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
 		Debug|x64 = Debug|x64
diff --git a/runtime/C/C.vcproj b/runtime/C/C.vcproj
index 16d9c2b..25aaf8b 100644
--- a/runtime/C/C.vcproj
+++ b/runtime/C/C.vcproj
@@ -5,9 +5,6 @@
 	Name="C"
 	ProjectGUID="{0F0FE03A-78F3-4B34-9DCE-0CDFF1FB5C40}"
 	RootNamespace="C"
-	SccProjectName="Perforce Project"
-	SccLocalPath="..\.."
-	SccProvider="MSSCCI:Perforce SCM"
 	Keyword="Win32Proj"
 	TargetFrameworkVersion="131072"
 	>
diff --git a/runtime/C/dist/libantlr3c-3.1.4-SNAPSHOT.tar.gz b/runtime/C/dist/libantlr3c-3.1.4-SNAPSHOT.tar.gz
new file mode 100644
index 0000000..a9ad784
--- /dev/null
+++ b/runtime/C/dist/libantlr3c-3.1.4-SNAPSHOT.tar.gz
Binary files differ
diff --git a/runtime/C/dist/libantlr3c-3.3.1-SNAPSHOT.tar.gz b/runtime/C/dist/libantlr3c-3.3.1-SNAPSHOT.tar.gz
new file mode 100644
index 0000000..ca21cf7
--- /dev/null
+++ b/runtime/C/dist/libantlr3c-3.3.1-SNAPSHOT.tar.gz
Binary files differ
diff --git a/runtime/C/dist/libantlr3c-3.4-beta3.tar.gz b/runtime/C/dist/libantlr3c-3.4-beta3.tar.gz
new file mode 100644
index 0000000..f5e9fbb
--- /dev/null
+++ b/runtime/C/dist/libantlr3c-3.4-beta3.tar.gz
Binary files differ
diff --git a/runtime/C/dist/libantlr3c-3.4.tar.gz b/runtime/C/dist/libantlr3c-3.4.tar.gz
deleted file mode 100644
index daeb313..0000000
--- a/runtime/C/dist/libantlr3c-3.4.tar.gz
+++ /dev/null
Binary files differ
diff --git a/runtime/C/include/antlr3convertutf.h b/runtime/C/include/antlr3convertutf.h
index 79cc82c..e0c5603 100644
--- a/runtime/C/include/antlr3convertutf.h
+++ b/runtime/C/include/antlr3convertutf.h
@@ -118,8 +118,6 @@
 #define UNI_SUR_HIGH_END    (UTF32)0xDBFF
 #define UNI_SUR_LOW_START   (UTF32)0xDC00
 #define UNI_SUR_LOW_END     (UTF32)0xDFFF
-#define false	            ANTLR3_FALSE
-#define true	            ANTLR3_TRUE
 #define halfShift           ((UTF32)10)
 #define halfBase            ((UTF32)0x0010000UL)
 #define halfMask            ((UTF32)0x3FFUL)
diff --git a/runtime/C/include/antlr3debugeventlistener.h b/runtime/C/include/antlr3debugeventlistener.h
index c9cd6ce..1d1b38e 100644
--- a/runtime/C/include/antlr3debugeventlistener.h
+++ b/runtime/C/include/antlr3debugeventlistener.h
@@ -73,7 +73,7 @@
 	/** The version of the debugging protocol supported by the providing
 	 *  instance of the debug event listener.
 	 */
-	int					PROTOCOL_VERSION;
+	int					protocol_version;
 
 	/// The name of the grammar file that we are debugging
 	///
diff --git a/runtime/C/include/antlr3defs.h b/runtime/C/include/antlr3defs.h
index 2435b02..84efd01 100644
--- a/runtime/C/include/antlr3defs.h
+++ b/runtime/C/include/antlr3defs.h
@@ -111,6 +111,10 @@
 # define	ANTLR3_WIN64
 # define	ANTLR3_USE_64BIT
 
+#elif __LP64__
+
+# define ANTLR3_USE_64BIT
+
 #else
 
 #ifdef	_WIN32
diff --git a/runtime/C/src/antlr3baserecognizer.c b/runtime/C/src/antlr3baserecognizer.c
index e2eccc6..8c6b105 100644
--- a/runtime/C/src/antlr3baserecognizer.c
+++ b/runtime/C/src/antlr3baserecognizer.c
@@ -345,8 +345,8 @@
 	case    ANTLR3_TOKENSTREAM:
 
 		ex->token		= cts->tstream->_LT						(cts->tstream, 1);	    /* Current input token			    */
-		ex->line		= ((pANTLR3_COMMON_TOKEN)(ex->token))->getLine			(ex->token);
-		ex->charPositionInLine	= ((pANTLR3_COMMON_TOKEN)(ex->token))->getCharPositionInLine	(ex->token);
+		ex->line		= ((pANTLR3_COMMON_TOKEN)(ex->token))->getLine			((pANTLR3_COMMON_TOKEN)(ex->token));
+		ex->charPositionInLine	= ((pANTLR3_COMMON_TOKEN)(ex->token))->getCharPositionInLine	((pANTLR3_COMMON_TOKEN)(ex->token));
 		ex->index		= cts->tstream->istream->index					(cts->tstream->istream);
 		if	(((pANTLR3_COMMON_TOKEN)(ex->token))->type == ANTLR3_TOKEN_EOF)
 		{
@@ -362,8 +362,8 @@
 	case    ANTLR3_COMMONTREENODE:
 
 		ex->token		= tns->_LT						    (tns, 1);	    /* Current input tree node			    */
-		ex->line		= ((pANTLR3_BASE_TREE)(ex->token))->getLine		    (ex->token);
-		ex->charPositionInLine	= ((pANTLR3_BASE_TREE)(ex->token))->getCharPositionInLine   (ex->token);
+		ex->line		= ((pANTLR3_BASE_TREE)(ex->token))->getLine		    ((pANTLR3_BASE_TREE)(ex->token));
+		ex->charPositionInLine	= ((pANTLR3_BASE_TREE)(ex->token))->getCharPositionInLine   ((pANTLR3_BASE_TREE)(ex->token));
 		ex->index		= tns->istream->index					    (tns->istream);
 
 		// Are you ready for this? Deep breath now...
@@ -586,7 +586,7 @@
 		// EOR can follow, but if we are not the start symbol, we
 		// need to remove it.
 		//
-		if	(recognizer->state->following->vector->count >= 0)
+		//if	(recognizer->state->following->vector->count >= 0) ml: always true
 		{
 			followClone->remove(followClone, ANTLR3_EOR_TOKEN_TYPE);
 		}
@@ -1589,7 +1589,7 @@
 	{
 		// We can fake the missing token and proceed
 		//
-		matchedSymbol = recognizer->getMissingSymbol(recognizer, is, recognizer->state->exception, ANTLR3_TOKEN_INVALID, follow);
+		matchedSymbol = (pANTLR3_COMMON_TOKEN)recognizer->getMissingSymbol(recognizer, is, recognizer->state->exception, ANTLR3_TOKEN_INVALID, follow);
 		recognizer->state->exception->type	= ANTLR3_MISSING_TOKEN_EXCEPTION;
 		recognizer->state->exception->token	= matchedSymbol;
 
@@ -2142,6 +2142,13 @@
 		}
 	}
 	
+  // ml: 2013-11-05, added reset of old exceptions.
+  pANTLR3_EXCEPTION thisE = recognizer->state->exception;
+  if	(thisE != NULL)
+  {
+    thisE->freeEx(thisE);
+    recognizer->state->exception = NULL;
+  }
 
     // Install a new following set
     //
@@ -2196,6 +2203,7 @@
 		recognizer->state->tokFactory = antlr3TokenFactoryNew(current->input);
 	}
 	token	= recognizer->state->tokFactory->newToken(recognizer->state->tokFactory);
+	if (token == NULL) { return NULL; }
 
 	// Set some of the token properties based on the current token
 	//
diff --git a/runtime/C/src/antlr3basetree.c b/runtime/C/src/antlr3basetree.c
index bbc81e7..f191f6f 100644
--- a/runtime/C/src/antlr3basetree.c
+++ b/runtime/C/src/antlr3basetree.c
@@ -187,13 +187,16 @@
                 for (i = 0; i < n; i++)
                 {
                     pANTLR3_BASE_TREE entry;
-                    entry = child->children->get(child->children, i);
+                    entry = (pANTLR3_BASE_TREE)child->children->get(child->children, i);
 
                     // ANTLR3 lists can be sparse, unlike Array Lists
                     //
                     if (entry != NULL)
                     {
-                        tree->children->add(tree->children, entry, (void (ANTLR3_CDECL *) (void *))child->free);
+                        ANTLR3_UINT32 count = tree->children->add(tree->children, entry, (void (ANTLR3_CDECL *) (void *))child->free);
+
+                        entry->setChildIndex(entry, count - 1);
+                        entry->setParent(entry, tree);
                     }
                 }
             }
@@ -211,8 +214,9 @@
 			tree->createChildrenList(tree);
 		}
 
-		tree->children->add(tree->children, child, (void (ANTLR3_CDECL *)(void *))child->free);
-		
+		ANTLR3_UINT32 count = tree->children->add(tree->children, child, (void (ANTLR3_CDECL *)(void *))child->free);
+		child->setChildIndex(child, count - 1);
+		child->setParent(child, tree);
 	}
 }
 
@@ -260,7 +264,7 @@
 	ANTLR3_UINT32	i;
 	ANTLR3_UINT32	s;
 
-	newTree = tree->dupNode	    (tree);
+	newTree = (pANTLR3_BASE_TREE)tree->dupNode	    (tree);
 
 	if	(tree->children != NULL)
 	{
@@ -275,7 +279,7 @@
 
 			if  (t!= NULL)
 			{
-				newNode	    = t->dupTree(t);
+				newNode	    = (pANTLR3_BASE_TREE)t->dupTree(t);
 				newTree->addChild(newTree, newNode);
 			}
 		}
@@ -480,7 +484,7 @@
 	{
 		pANTLR3_BASE_TREE	child;
 
-		child = tree->getChild(tree, c);
+		child = (pANTLR3_BASE_TREE)tree->getChild(tree, c);
 
 		child->setChildIndex(child, c);
 		child->setParent(child, tree);
diff --git a/runtime/C/src/antlr3basetreeadaptor.c b/runtime/C/src/antlr3basetreeadaptor.c
index e35878f..1f42751 100644
--- a/runtime/C/src/antlr3basetreeadaptor.c
+++ b/runtime/C/src/antlr3basetreeadaptor.c
@@ -192,7 +192,7 @@
 
 		// Pick up a pointer for the child
 		//
-		child = adaptor->getChild(adaptor, t, i);
+		child = (pANTLR3_BASE_TREE)adaptor->getChild(adaptor, t, i);
 
 		// Name the node
 		//
@@ -275,7 +275,7 @@
 
 		// Next child
 		//
-		child	= adaptor->getChild(adaptor, t, i);
+		child	= (pANTLR3_BASE_TREE)adaptor->getChild(adaptor, t, i);
 
 		// Create the edge relation
 		//
@@ -440,7 +440,7 @@
 static	pANTLR3_BASE_TREE	
 nilNode	    (pANTLR3_BASE_TREE_ADAPTOR adaptor)
 {
-	return	adaptor->create(adaptor, NULL);
+	return	(pANTLR3_BASE_TREE)adaptor->create(adaptor, NULL);
 }
 
 static	pANTLR3_BASE_TREE	
@@ -448,7 +448,7 @@
 {
 	pANTLR3_BASE_TREE t;
 
-	t = adaptor->create				(adaptor, NULL);
+	t = (pANTLR3_BASE_TREE)adaptor->create				(adaptor, NULL);
 	adaptor->debugger->createNode	(adaptor->debugger, t);
 
 	return	t;
@@ -460,7 +460,7 @@
 static	pANTLR3_BASE_TREE	
 dupTree  (pANTLR3_BASE_TREE_ADAPTOR adaptor, pANTLR3_BASE_TREE t)
 {
-	return	adaptor->dupTreeTT(adaptor, t, NULL);
+	return	(pANTLR3_BASE_TREE)adaptor->dupTreeTT(adaptor, t, NULL);
 }
 
 pANTLR3_BASE_TREE
@@ -476,7 +476,7 @@
 	{
 		return NULL;
 	}
-	newTree = t->dupNode(t);
+	newTree = (pANTLR3_BASE_TREE)t->dupNode(t);
 
 	// Ensure new subtree root has parent/child index set
 	//
@@ -486,8 +486,8 @@
 
 	for	(i=0; i < n; i++)
 	{
-		child = adaptor->getChild		(adaptor, t, i);
-		newSubTree = adaptor->dupTreeTT	(adaptor, child, t);
+		child = (pANTLR3_BASE_TREE)adaptor->getChild		(adaptor, t, i);
+		newSubTree = (pANTLR3_BASE_TREE)adaptor->dupTreeTT	(adaptor, child, t);
 		adaptor->addChild				(adaptor, newTree, newSubTree);
 	}
 	return	newTree;
@@ -510,7 +510,7 @@
 	n = adaptor->getChildCount(adaptor, tree);
 	for	(i = 0; i < n; i++)
 	{
-		child = adaptor->getChild(adaptor, tree, i);
+		child = (pANTLR3_BASE_TREE)adaptor->getChild(adaptor, tree, i);
 		simulateTreeConstruction(adaptor, child);
 		adaptor->debugger->addChild(adaptor->debugger, tree, child);
 	}
@@ -523,7 +523,7 @@
 
 	// Call the normal dup tree mechanism first
 	//
-	t = adaptor->dupTreeTT(adaptor, tree, NULL);
+	t = (pANTLR3_BASE_TREE)adaptor->dupTreeTT(adaptor, tree, NULL);
 
 	// In order to tell the debugger what we have just done, we now
 	// simulate the tree building mechanism. THis will fire
@@ -578,7 +578,7 @@
 
 	if	(t != NULL && child != NULL)
 	{
-		tc = adaptor->create(adaptor, child);
+		tc = (pANTLR3_BASE_TREE)adaptor->create(adaptor, child);
 		adaptor->addChild(adaptor, t, tc);
 		adaptor->debugger->addChild(adaptor->debugger, t, tc);
 	}
@@ -654,7 +654,7 @@
          * because if it was a Nil Node, then we can reuse it now.
 		 */
         saveRoot    = newRootTree;
-		newRootTree = newRootTree->getChild(newRootTree, 0);
+		newRootTree = (pANTLR3_BASE_TREE)newRootTree->getChild(newRootTree, 0);
 
         // Reclaim the old nilNode()
         //
@@ -718,7 +718,7 @@
 		}
 		else if	(root->getChildCount(root) == 1)
 		{
-			root = root->getChild(root, 0);
+			root = (pANTLR3_BASE_TREE)root->getChild(root, 0);
 			root->setParent(root, NULL);
 			root->setChildIndex(root, -1);
 
@@ -739,14 +739,14 @@
 static	pANTLR3_BASE_TREE	
    becomeRootToken	(pANTLR3_BASE_TREE_ADAPTOR adaptor, void * newRoot, pANTLR3_BASE_TREE oldRoot)
 {
-	return	adaptor->becomeRoot(adaptor, adaptor->create(adaptor, newRoot), oldRoot);
+	return	(pANTLR3_BASE_TREE)adaptor->becomeRoot(adaptor, adaptor->create(adaptor, (pANTLR3_COMMON_TOKEN)newRoot), oldRoot);
 }
 static	pANTLR3_BASE_TREE	
 dbgBecomeRootToken	(pANTLR3_BASE_TREE_ADAPTOR adaptor, void * newRoot, pANTLR3_BASE_TREE oldRoot)
 {
 	pANTLR3_BASE_TREE	t;
 
-	t =	adaptor->becomeRoot(adaptor, adaptor->create(adaptor, newRoot), oldRoot);
+	t =	(pANTLR3_BASE_TREE)adaptor->becomeRoot(adaptor, adaptor->create(adaptor, (pANTLR3_COMMON_TOKEN)newRoot), oldRoot);
 
 	adaptor->debugger->becomeRoot(adaptor->debugger,t, oldRoot);
 
@@ -769,7 +769,7 @@
 
 	/* Return a new node based upon this token
 	 */
-	return	adaptor->create(adaptor, fromToken);
+	return	(pANTLR3_BASE_TREE)adaptor->create(adaptor, fromToken);
 }
 static	pANTLR3_BASE_TREE	
 dbgCreateTypeToken	(pANTLR3_BASE_TREE_ADAPTOR adaptor, ANTLR3_UINT32 tokenType, pANTLR3_COMMON_TOKEN fromToken)
@@ -800,7 +800,7 @@
 
 	/* Return a new node based upon this token
 	 */
-	return	adaptor->create(adaptor, fromToken);
+	return	(pANTLR3_BASE_TREE)adaptor->create(adaptor, fromToken);
 }
 static	pANTLR3_BASE_TREE	
 dbgCreateTypeTokenText	(pANTLR3_BASE_TREE_ADAPTOR adaptor, ANTLR3_UINT32 tokenType, pANTLR3_COMMON_TOKEN fromToken, pANTLR3_UINT8 text)
@@ -825,7 +825,7 @@
 
 	/* Return a new node based upon this token
 	 */
-	return	adaptor->create(adaptor, fromToken);
+	return	(pANTLR3_BASE_TREE)adaptor->create(adaptor, fromToken);
 }
 static	pANTLR3_BASE_TREE	
    dbgCreateTypeText	(pANTLR3_BASE_TREE_ADAPTOR adaptor, ANTLR3_UINT32 tokenType, pANTLR3_UINT8 text)
diff --git a/runtime/C/src/antlr3bitset.c b/runtime/C/src/antlr3bitset.c
index 4e63c79..4434ed1 100644
--- a/runtime/C/src/antlr3bitset.c
+++ b/runtime/C/src/antlr3bitset.c
@@ -101,14 +101,13 @@
 	numelements	= ((numBits -1) >> ANTLR3_BITSET_LOG_BITS) + 1;
 
 	bitset->blist.bits    = (pANTLR3_BITWORD) ANTLR3_MALLOC((size_t)(numelements * sizeof(ANTLR3_BITWORD)));
-	memset(bitset->blist.bits, 0, (size_t)(numelements * sizeof(ANTLR3_BITWORD)));
-	bitset->blist.length  = numelements;
-
 	if	(bitset->blist.bits == NULL)
 	{
 		ANTLR3_FREE(bitset);
 		return	NULL;
 	}
+	memset(bitset->blist.bits, 0, (size_t)(numelements * sizeof(ANTLR3_BITWORD)));
+	bitset->blist.length  = numelements;
 
 	antlr3BitsetSetAPI(bitset);
 
diff --git a/runtime/C/src/antlr3collections.c b/runtime/C/src/antlr3collections.c
index d9e22e9..9d79edd 100644
--- a/runtime/C/src/antlr3collections.c
+++ b/runtime/C/src/antlr3collections.c
@@ -97,7 +97,7 @@
 static	ANTLR3_UINT32		antlr3VectorSize    (pANTLR3_VECTOR vector);
 static	ANTLR3_BOOLEAN      antlr3VectorSwap	(pANTLR3_VECTOR vector, ANTLR3_UINT32 entry1, ANTLR3_UINT32 entry2);
 
-static  void                newPool             (pANTLR3_VECTOR_FACTORY factory);
+static  ANTLR3_BOOLEAN      newPool             (pANTLR3_VECTOR_FACTORY factory);
 static  void				closeVectorFactory  (pANTLR3_VECTOR_FACTORY factory);
 static	pANTLR3_VECTOR		newVector			(pANTLR3_VECTOR_FACTORY factory);
 static	void				returnVector		(pANTLR3_VECTOR_FACTORY factory, pANTLR3_VECTOR vector);
@@ -132,7 +132,7 @@
 
 	ANTLR3_UINT32	bucket;	// Used to traverse the buckets
 
-	table   = ANTLR3_MALLOC(sizeof(ANTLR3_HASH_TABLE));
+	table   = (pANTLR3_HASH_TABLE)ANTLR3_MALLOC(sizeof(ANTLR3_HASH_TABLE));
 
 	// Error out if no memory left
 	if	(table	== NULL)
@@ -653,7 +653,7 @@
     }
     else
     {
-        entry->keybase.key.sKey	= key;                  /* Record the key value								*/
+        entry->keybase.key.sKey	= (pANTLR3_UINT8)key;                  /* Record the key value								*/
     }
 	entry->nextEntry		= NULL;					/* Ensure that the forward pointer ends the chain   */
 
@@ -1285,7 +1285,7 @@
 	return  element;
 }
 
-static  void
+static  ANTLR3_BOOLEAN
 antlr3VectorResize  (pANTLR3_VECTOR vector, ANTLR3_UINT32 hint)
 {
 	ANTLR3_UINT32	newSize;
@@ -1310,7 +1310,13 @@
         // We were already larger than the internal size, so we just
         // use realloc so that the pointers are copied for us
         //
-        vector->elements	= (pANTLR3_VECTOR_ELEMENT)ANTLR3_REALLOC(vector->elements, (sizeof(ANTLR3_VECTOR_ELEMENT)* newSize));
+		pANTLR3_VECTOR_ELEMENT newElements = (pANTLR3_VECTOR_ELEMENT)ANTLR3_REALLOC(vector->elements, (sizeof(ANTLR3_VECTOR_ELEMENT)* newSize));
+		if (newElements == NULL)
+		{
+			// realloc failed, but the old allocation is still there
+			return ANTLR3_FALSE;
+		}
+        vector->elements = newElements;
     }
     else
     {
@@ -1320,10 +1326,16 @@
         // is part of the internal or external entries, so we copy the internal ones to the new space
         //
         vector->elements	= (pANTLR3_VECTOR_ELEMENT)ANTLR3_MALLOC((sizeof(ANTLR3_VECTOR_ELEMENT)* newSize));
+		if (vector->elements == NULL)
+		{
+			// malloc failed
+			return ANTLR3_FALSE;
+		}
         ANTLR3_MEMCPY(vector->elements, vector->internal, ANTLR3_VECTOR_INTERNAL_SIZE * sizeof(ANTLR3_VECTOR_ELEMENT));
     }
 
 	vector->elementsSize	= newSize;
+	return ANTLR3_TRUE;
 }
 
 /// Add the supplied pointer and freeing function pointer to the list,
@@ -1335,7 +1347,12 @@
 	//
 	if	(vector->count == vector->elementsSize)
 	{
-		antlr3VectorResize(vector, 0);	    // Give no hint, we let it add 1024 or double it
+		// Give no hint, we let it add 1024 or double it
+		if (!antlr3VectorResize(vector, 0))
+		{
+			// Resize failed
+			return 0;
+		}
 	}
 
 	// Insert the new entry
@@ -1360,7 +1377,12 @@
 	//
 	if (entry >= vector->elementsSize)
 	{
-		antlr3VectorResize(vector, entry);	// We will get at least this many 
+		// We will get at least this many
+		if (!antlr3VectorResize(vector, entry))
+		{
+			// Resize failed
+			return 0;
+		}
 	}
 
 	// Valid request, replace the current one, freeing any prior entry if told to
@@ -1491,25 +1513,40 @@
 	// TODO: remove this line once happy printf("Returned vector %08X to the pool, stack size is %d\n", vector, factory->freeStack->size(factory->freeStack));
 }
 
-static void
+static ANTLR3_BOOLEAN
 newPool(pANTLR3_VECTOR_FACTORY factory)
 {
+	pANTLR3_VECTOR *newPools;
+
     /* Increment factory count
      */
-    factory->thisPool++;
+    ++factory->thisPool;
 
     /* Ensure we have enough pointers allocated
      */
-    factory->pools = (pANTLR3_VECTOR *)
-		     ANTLR3_REALLOC(	(void *)factory->pools,	    /* Current pools pointer (starts at NULL)	*/
+	newPools = (pANTLR3_VECTOR *)
+		ANTLR3_REALLOC(	(void *)factory->pools,	    /* Current pools pointer (starts at NULL)	*/
 					(ANTLR3_UINT32)((factory->thisPool + 1) * sizeof(pANTLR3_VECTOR *))	/* Memory for new pool pointers */
 					);
+	if (newPools == NULL)
+	{
+		// realloc failed, but we still have the old allocation
+		--factory->thisPool;
+		return ANTLR3_FALSE;
+	}
+	factory->pools = newPools;
 
     /* Allocate a new pool for the factory
      */
     factory->pools[factory->thisPool]	=
 			    (pANTLR3_VECTOR)
 				ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_VECTOR) * ANTLR3_FACTORY_VPOOL_SIZE));
+	if (factory->pools[factory->thisPool] == NULL)
+	{
+		// malloc failed
+		--factory->thisPool;
+		return ANTLR3_FALSE;
+	}
 
 
     /* Reset the counters
@@ -1518,7 +1555,7 @@
 
     /* Done
      */
-    return;
+    return ANTLR3_TRUE;
 }
 
 static  void		
@@ -1641,7 +1678,7 @@
 
 	// If we have anything on the re claim stack, reuse it
 	//
-	vector = factory->freeStack->peek(factory->freeStack);
+	vector = (pANTLR3_VECTOR)factory->freeStack->peek(factory->freeStack);
 
 	if  (vector != NULL)
 	{
@@ -1661,7 +1698,11 @@
     {
         // We ran out of vectors in the current pool, so we need a new pool
         //
-        newPool(factory);
+        if (!newPool(factory))
+		{
+			// new pool creation failed
+			return NULL;
+		}
     }
 
     // Assuming everything went well (we are trying for performance here so doing minimal
@@ -1676,7 +1717,7 @@
     vector->factoryMade = ANTLR3_TRUE;
 
     // We know that the pool vectors are created at the default size, which means they
-    // will start off using their internal entry pointers. We must intialize our pool vector
+    // will start off using their internal entry pointers. We must initialize our pool vector
     // to point to its own internal entry table and not the pre-made one.
     //
     vector->elements = vector->internal;
@@ -1893,7 +1934,6 @@
     pANTLR3_INT_TRIE_NODE   p;
 
     p=trie->root;
-    key = key;
 
     return ANTLR3_FALSE;
 }
@@ -2337,7 +2377,7 @@
     {
         // We don't have any edges yet, so create an array to hold them
         //
-        topo->edges = ANTLR3_CALLOC(sizeof(pANTLR3_BITSET) * (maxEdge + 1), 1);
+        topo->edges = (pANTLR3_BITSET*)ANTLR3_CALLOC(sizeof(pANTLR3_BITSET) * (maxEdge + 1), 1);
         if (topo->edges == NULL)
         {
             return;
@@ -2351,7 +2391,7 @@
     {
         // WE have some edges but not enough
         //
-        topo->edges = ANTLR3_REALLOC(topo->edges, sizeof(pANTLR3_BITSET) * (maxEdge + 1));
+        topo->edges = (pANTLR3_BITSET*)ANTLR3_REALLOC(topo->edges, sizeof(pANTLR3_BITSET) * (maxEdge + 1));
         if (topo->edges == NULL)
         {
             return;
@@ -2529,14 +2569,22 @@
     //
     if  (topo->edges == NULL)
     {
-        return 0;
+        return NULL;
     }
     // First we need a vector to populate with enough
-    // entries to accomodate the sorted list and another to accomodate
+    // entries to accommodate the sorted list and another to accommodate
     // the maximum cycle we could detect which is all nodes such as 0->1->2->3->0
     //
-    topo->sorted    = ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
-    topo->cycle     = ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
+    topo->sorted    = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
+	if (topo->sorted == NULL)
+	{
+		return NULL;
+	}
+    topo->cycle     = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
+	if (topo->cycle == NULL)
+	{
+		return NULL;
+	}
 
     // Next we need an empty bitset to show whether we have visited a node
     // or not. This is the bit that gives us linear time of course as we are essentially
@@ -2595,7 +2643,7 @@
     // we are given. This is just a convenience routine that allows you to
     // sort the children of a tree node into topological order before or
     // during an AST walk. This can be useful for optimizations that require
-    // dag reorders and also when the input stream defines thigns that are
+    // dag reorders and also when the input stream defines things that are
     // interdependent and you want to walk the list of the generated trees
     // for those things in topological order so you can ignore the interdependencies
     // at that point.
@@ -2621,8 +2669,8 @@
     }
 
     // Ensure that the vector we are sorting is at least as big as the
-    // the input sequence we were adsked to sort. It does not matter if it is
-    // bigger as thaat probably just means that nodes numbered higher than the
+    // the input sequence we were asked to sort. It does not matter if it is
+    // bigger as that probably just means that nodes numbered higher than the
     // limit had no dependencies and so can be left alone.
     //
     if  (topo->limit > v->count)
@@ -2636,10 +2684,15 @@
     // We need to know the locations of each of the entries
     // in the vector as we don't want to duplicate them in a new vector. We
     // just use an indirection table to get the vector entry for a particular sequence
-    // acording to where we moved it last. Then we can just swap vector entries until
+    // according to where we moved it last. Then we can just swap vector entries until
     // we are done :-)
     //
-    vIndex = ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
+    vIndex = (pANTLR3_UINT32)ANTLR3_MALLOC(topo->limit * sizeof(ANTLR3_UINT32));
+	if (vIndex == NULL)
+	{
+		// malloc failed
+		return;
+	}
 
     // Start index, each vector entry is located where you think it is
     //
diff --git a/runtime/C/src/antlr3commontoken.c b/runtime/C/src/antlr3commontoken.c
index 2627431..da4ef63 100644
--- a/runtime/C/src/antlr3commontoken.c
+++ b/runtime/C/src/antlr3commontoken.c
@@ -65,7 +65,7 @@
 
 /* Internal management functions
  */
-static	void			newPool		(pANTLR3_TOKEN_FACTORY factory);
+static	ANTLR3_BOOLEAN			newPool		(pANTLR3_TOKEN_FACTORY factory);
 static	pANTLR3_COMMON_TOKEN    newPoolToken	(pANTLR3_TOKEN_FACTORY factory);
 
 
@@ -148,30 +148,44 @@
     }
 }
 
-static void
+static ANTLR3_BOOLEAN
 newPool(pANTLR3_TOKEN_FACTORY factory)
 {
     /* Increment factory count
      */
-    factory->thisPool++;
+    ++(factory->thisPool);
 
     // If we were reusing this token factory then we may already have a pool
-    // allocated. If we exceeded the max avaible then we must allocate a new
+    // allocated. If we exceeded the max available then we must allocate a new
     // one.
     if  (factory->thisPool > factory->maxPool)
     {
         /* Ensure we have enough pointers allocated
          */
-        factory->pools = (pANTLR3_COMMON_TOKEN *)
-		         ANTLR3_REALLOC(	(void *)factory->pools,	    /* Current pools pointer (starts at NULL)	*/
-					    (ANTLR3_UINT32)((factory->thisPool + 1) * sizeof(pANTLR3_COMMON_TOKEN *))	/* Memory for new pool pointers */
-					    );
+		pANTLR3_COMMON_TOKEN *newPools = (pANTLR3_COMMON_TOKEN *)
+			ANTLR3_REALLOC((void *)factory->pools,	    /* Current pools pointer (starts at NULL)	*/
+		                   (ANTLR3_UINT32)((factory->thisPool + 1) * sizeof(pANTLR3_COMMON_TOKEN *))	/* Memory for new pool pointers */
+			);
+		if (newPools == NULL)
+		{
+			// We are out of memory, but the old allocation is still valid for now
+			--(factory->thisPool);
+			return ANTLR3_FALSE;
+		}
+
+        factory->pools = newPools;
 
         /* Allocate a new pool for the factory
          */
         factory->pools[factory->thisPool]	=
 			        (pANTLR3_COMMON_TOKEN) 
 				    ANTLR3_CALLOC(1, (size_t)(sizeof(ANTLR3_COMMON_TOKEN) * ANTLR3_FACTORY_POOL_SIZE));
+		if (factory->pools[factory->thisPool] == NULL)
+		{
+			// Allocation failed
+			--(factory->thisPool);
+			return ANTLR3_FALSE;
+		}
 
         // We now have a new pool and can track it as the maximum we have created so far
         //
@@ -184,7 +198,7 @@
   
     /* Done
      */
-    return;
+    return ANTLR3_TRUE;
 }
 
 static pANTLR3_COMMON_TOKEN
@@ -192,6 +206,8 @@
 {
     pANTLR3_COMMON_TOKEN token;
 
+	if (factory == NULL) { return NULL; }
+
     /* See if we need a new token pool before allocating a new
      * one
      */
@@ -199,9 +215,16 @@
     {
         /* We ran out of tokens in the current pool, so we need a new pool
          */
-        newPool(factory);
+        if (!newPool(factory))
+		{
+			return NULL;
+		}
     }
 
+	// make sure the factory is sane
+	if (factory->pools == NULL) { return NULL; }
+	if (factory->pools[factory->thisPool] == NULL) { return NULL; }
+
     /* Assuming everything went well (we are trying for performance here so doing minimal
      * error checking. Then we can work out what the pointer is to the next token.
      */
diff --git a/runtime/C/src/antlr3commontree.c b/runtime/C/src/antlr3commontree.c
index 65de38f..e275263 100644
--- a/runtime/C/src/antlr3commontree.c
+++ b/runtime/C/src/antlr3commontree.c
@@ -55,7 +55,7 @@
 
 // Factory functions for the Arboretum
 //
-static void					newPool				(pANTLR3_ARBORETUM factory);
+static ANTLR3_BOOLEAN		newPool				(pANTLR3_ARBORETUM factory);
 static pANTLR3_BASE_TREE    newPoolTree			(pANTLR3_ARBORETUM factory);
 static pANTLR3_BASE_TREE    newFromTree			(pANTLR3_ARBORETUM factory, pANTLR3_COMMON_TREE tree);
 static pANTLR3_BASE_TREE    newFromToken		(pANTLR3_ARBORETUM factory, pANTLR3_COMMON_TOKEN token);
@@ -120,25 +120,40 @@
 
 }
 
-static void
+static ANTLR3_BOOLEAN
 newPool(pANTLR3_ARBORETUM factory)
 {
+	pANTLR3_COMMON_TREE *newPools;
+
     // Increment factory count
     //
-    factory->thisPool++;
+    ++factory->thisPool;
 
     // Ensure we have enough pointers allocated
     //
-    factory->pools = (pANTLR3_COMMON_TREE *)
+    newPools = (pANTLR3_COMMON_TREE *)
 					ANTLR3_REALLOC(	(void *)factory->pools,										// Current pools pointer (starts at NULL)
 					(ANTLR3_UINT32)((factory->thisPool + 1) * sizeof(pANTLR3_COMMON_TREE *))	// Memory for new pool pointers
 					);
+	if (newPools == NULL)
+	{
+		// realloc failed, but we still have the old allocation
+		--factory->thisPool;
+		return ANTLR3_FALSE;
+	}
+	factory->pools = newPools;
 
     // Allocate a new pool for the factory
     //
     factory->pools[factory->thisPool]	=
 			    (pANTLR3_COMMON_TREE) 
 				ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_COMMON_TREE) * ANTLR3_FACTORY_POOL_SIZE));
+	if (factory->pools[factory->thisPool] == NULL)
+	{
+		// malloc failed
+		--factory->thisPool;
+		return ANTLR3_FALSE;
+	}
 
 
     // Reset the counters
@@ -147,7 +162,7 @@
   
     // Done
     //
-    return;
+    return ANTLR3_TRUE;
 }
 
 static	pANTLR3_BASE_TREE    
@@ -157,7 +172,7 @@
 
     // If we have anything on the re claim stack, reuse that sucker first
     //
-    tree = factory->nilStack->peek(factory->nilStack);
+    tree = (pANTLR3_COMMON_TREE)factory->nilStack->peek(factory->nilStack);
 
     if  (tree != NULL)
     {
@@ -176,7 +191,11 @@
 	{
 		// We ran out of tokens in the current pool, so we need a new pool
 		//
-		newPool(factory);
+		if (!newPool(factory))
+		{
+			// new pool creation failed
+			return NULL;
+		}
 	}
 
 	// Assuming everything went well - we are trying for performance here so doing minimal
@@ -337,7 +356,7 @@
 antlr3CommonTreeNew()
 {
 	pANTLR3_COMMON_TREE	tree;
-	tree    = ANTLR3_CALLOC(1, sizeof(ANTLR3_COMMON_TREE));
+	tree = (pANTLR3_COMMON_TREE)ANTLR3_CALLOC(1, sizeof(ANTLR3_COMMON_TREE));
 
 	if	(tree == NULL)
 	{
@@ -503,13 +522,15 @@
 static pANTLR3_BASE_TREE	
 getParent				(pANTLR3_BASE_TREE tree)
 {
+	if (((pANTLR3_COMMON_TREE)(tree->super))->parent == NULL)
+		return NULL;
 	return & (((pANTLR3_COMMON_TREE)(tree->super))->parent->baseTree);
 }
 
 static void					
 setParent				(pANTLR3_BASE_TREE tree, pANTLR3_BASE_TREE parent)
 {
-	((pANTLR3_COMMON_TREE)(tree->super))->parent = parent == NULL ? NULL : ((pANTLR3_COMMON_TREE)(parent->super))->parent;
+	((pANTLR3_COMMON_TREE)(tree->super))->parent = parent == NULL ? NULL : ((pANTLR3_COMMON_TREE)(parent->super));
 }
 
 static void    				
diff --git a/runtime/C/src/antlr3commontreeadaptor.c b/runtime/C/src/antlr3commontreeadaptor.c
index abce6f0..38697f1 100644
--- a/runtime/C/src/antlr3commontreeadaptor.c
+++ b/runtime/C/src/antlr3commontreeadaptor.c
@@ -243,7 +243,7 @@
 	// need to track and free the memory allocated to it, so for now, we just
 	// want something in the tree that isn't a NULL pointer.
 	//
-	return adaptor->createTypeText(adaptor, ANTLR3_TOKEN_INVALID, (pANTLR3_UINT8)"Tree Error Node");
+	return (pANTLR3_BASE_TREE)adaptor->createTypeText(adaptor, ANTLR3_TOKEN_INVALID, (pANTLR3_UINT8)"Tree Error Node");
 
 }
 
@@ -252,7 +252,7 @@
 static	pANTLR3_BASE_TREE
 dupNode		(pANTLR3_BASE_TREE_ADAPTOR adaptor, pANTLR3_BASE_TREE treeNode)
 {
-	return  treeNode == NULL ? NULL : treeNode->dupNode(treeNode);
+	return  treeNode == NULL ? NULL : (pANTLR3_BASE_TREE)treeNode->dupNode(treeNode);
 }
 
 static	pANTLR3_BASE_TREE
@@ -453,7 +453,7 @@
 static	pANTLR3_BASE_TREE
 getChild				(pANTLR3_BASE_TREE_ADAPTOR adaptor, pANTLR3_BASE_TREE t, ANTLR3_UINT32 i)
 {
-	return t->getChild(t, i);
+	return (pANTLR3_BASE_TREE)t->getChild(t, i);
 }
 static  void
 setChild				(pANTLR3_BASE_TREE_ADAPTOR adaptor, pANTLR3_BASE_TREE t, ANTLR3_UINT32 i, pANTLR3_BASE_TREE child)
diff --git a/runtime/C/src/antlr3commontreenodestream.c b/runtime/C/src/antlr3commontreenodestream.c
index a759d34..54d5184 100644
--- a/runtime/C/src/antlr3commontreenodestream.c
+++ b/runtime/C/src/antlr3commontreenodestream.c
@@ -503,7 +503,7 @@
 	//
 	for	(c = 0; c < nCount; c++)
 	{
-		fillBuffer(ctns, ctns->adaptor->getChild(ctns->adaptor, t, c));
+		fillBuffer(ctns, (pANTLR3_BASE_TREE)ctns->adaptor->getChild(ctns->adaptor, t, c));
 	}
 
 	// If the tree had children and was not a nil (list) node, then we
@@ -560,7 +560,7 @@
 		return	&(tns->ctns->INVALID_NODE.baseTree);
 	}
 
-	return tns->ctns->nodes->get(tns->ctns->nodes, tns->ctns->p - k);
+	return (pANTLR3_BASE_TREE)tns->ctns->nodes->get(tns->ctns->nodes, tns->ctns->p - k);
 }
 
 /// Get tree node at current input pointer + i ahead where i=1 is next node.
@@ -597,7 +597,7 @@
 		return &(tns->ctns->EOF_NODE.baseTree);
 	}
 
-	return	tns->ctns->nodes->get(tns->ctns->nodes, tns->ctns->p + k - 1);
+	return	(pANTLR3_BASE_TREE)tns->ctns->nodes->get(tns->ctns->nodes, tns->ctns->p + k - 1);
 }
 
 /// Where is this stream pulling nodes from?  This is not the name, but
@@ -867,7 +867,7 @@
 	{
 		pANTLR3_BASE_TREE   child;
 
-		child = p->getChild(p, c);
+		child = (pANTLR3_BASE_TREE)p->getChild(p, c);
 		tns->toStringWork(tns, child, stop, buf);
 	}
 
@@ -947,7 +947,7 @@
 		fillBufferRoot(tns->ctns);
 	}
 
-	return tns->ctns->nodes->get(tns->ctns->nodes, k);
+	return (pANTLR3_BASE_TREE)tns->ctns->nodes->get(tns->ctns->nodes, k);
 }
 
 static	void
diff --git a/runtime/C/src/antlr3convertutf.c b/runtime/C/src/antlr3convertutf.c
index 7c2f060..9d2bcf1 100644
--- a/runtime/C/src/antlr3convertutf.c
+++ b/runtime/C/src/antlr3convertutf.c
@@ -288,25 +288,25 @@
     UTF8 a;
     const UTF8 *srcptr = source+length;
     switch (length) {
-    default: return false;
+    default: return ANTLR3_FALSE;
 	/* Everything else falls through when "true"... */
-    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
-    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
-    case 2: if ((a = (*--srcptr)) > 0xBF) return false;
+    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return ANTLR3_FALSE;
+    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return ANTLR3_FALSE;
+    case 2: if ((a = (*--srcptr)) > 0xBF) return ANTLR3_FALSE;
 
 	switch (*source) {
 	    /* no fall-through in this inner switch */
-	    case 0xE0: if (a < 0xA0) return false; break;
-	    case 0xED: if (a > 0x9F) return false; break;
-	    case 0xF0: if (a < 0x90) return false; break;
-	    case 0xF4: if (a > 0x8F) return false; break;
-	    default:   if (a < 0x80) return false;
+	    case 0xE0: if (a < 0xA0) return ANTLR3_FALSE; break;
+	    case 0xED: if (a > 0x9F) return ANTLR3_FALSE; break;
+	    case 0xF0: if (a < 0x90) return ANTLR3_FALSE; break;
+	    case 0xF4: if (a > 0x8F) return ANTLR3_FALSE; break;
+	    default:   if (a < 0x80) return ANTLR3_FALSE;
 	}
 
-    case 1: if (*source >= 0x80 && *source < 0xC2) return false;
+    case 1: if (*source >= 0x80 && *source < 0xC2) return ANTLR3_FALSE;
     }
-    if (*source > 0xF4) return false;
-    return true;
+    if (*source > 0xF4) return ANTLR3_FALSE;
+    return ANTLR3_TRUE;
 }
 
 /* --------------------------------------------------------------------- */
@@ -319,7 +319,7 @@
 isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
     int length = trailingBytesForUTF8[*source]+1;
     if (source+length > sourceEnd) {
-	return false;
+	return ANTLR3_FALSE;
     }
     return isLegalUTF8(source, length);
 }
diff --git a/runtime/C/src/antlr3debughandlers.c b/runtime/C/src/antlr3debughandlers.c
index d5f177a..5202e8e 100644
--- a/runtime/C/src/antlr3debughandlers.c
+++ b/runtime/C/src/antlr3debughandlers.c
@@ -94,7 +94,7 @@
 {
 	pANTLR3_DEBUG_EVENT_LISTENER	delboy;
 
-	delboy = ANTLR3_CALLOC(1, sizeof(ANTLR3_DEBUG_EVENT_LISTENER));
+	delboy = (pANTLR3_DEBUG_EVENT_LISTENER)ANTLR3_CALLOC(1, sizeof(ANTLR3_DEBUG_EVENT_LISTENER));
 
 	if	(delboy == NULL)
 	{
@@ -136,7 +136,7 @@
 	delboy->terminate				= terminate;
 	delboy->errorNode				= errorNode;
 
-	delboy->PROTOCOL_VERSION		= 2;	// ANTLR 3.1 is at protocol version 2
+	delboy->protocol_version		= 2;	// ANTLR 3.1 is at protocol version 2
 
 	delboy->port					= DEFAULT_DEBUGGER_PORT;
 
@@ -299,7 +299,7 @@
 		// Disable Nagle as this is essentially a chat exchange
 		//
 		optVal	= 1;
-		setsockopt(delboy->socket, SOL_SOCKET, TCP_NODELAY, (const void *)&optVal, sizeof(optVal));
+		setsockopt(delboy->socket, SOL_SOCKET, TCP_NODELAY, (const char *)&optVal, sizeof(optVal));
 		
 	}
 
@@ -307,7 +307,7 @@
 	// send it the protocol version we are using and what the name of the grammar
 	// is that we represent.
 	//
-	sprintf		(message, "ANTLR %d\n", delboy->PROTOCOL_VERSION);
+	sprintf		(message, "ANTLR %d\n", delboy->protocol_version);
 	sockSend	(delboy->socket, message, (int)strlen(message));
 	sprintf		(message, "grammar \"%s\n", delboy->grammarFileName->chars);
 	sockSend	(delboy->socket, message, (int)strlen(message));
diff --git a/runtime/C/src/antlr3inputstream.c b/runtime/C/src/antlr3inputstream.c
index e3f1c26..dd9f56e 100644
--- a/runtime/C/src/antlr3inputstream.c
+++ b/runtime/C/src/antlr3inputstream.c
@@ -263,7 +263,7 @@
 
     input->nextChar		= input->data;	/* Input at first character */
     input->line			= 1;		/* starts at line 1	    */
-    input->charPositionInLine	= -1;
+    input->charPositionInLine	= 0;
     input->currentLine		= input->data;
     input->markDepth		= 0;		/* Reset markers	    */
     
@@ -451,26 +451,32 @@
 
     /* New mark point 
      */
-    input->markDepth++;
+    ++input->markDepth;
 
     /* See if we are revisiting a mark as we can just reuse the vector
      * entry if we are, otherwise, we need a new one
      */
     if	(input->markDepth > input->markers->count)
     {	
-	state	= ANTLR3_MALLOC(sizeof(ANTLR3_LEX_STATE));
+		state = (pANTLR3_LEX_STATE)ANTLR3_MALLOC(sizeof(ANTLR3_LEX_STATE));
+		if (state == NULL)
+		{
+			// malloc failed
+			--input->markDepth;
+			return 0;
+		}
 
-	/* Add it to the table
-	 */
-	input->markers->add(input->markers, state, ANTLR3_FREE_FUNC);	/* No special structure, just free() on delete */
+		/* Add it to the table
+		 */
+		input->markers->add(input->markers, state, ANTLR3_FREE_FUNC);	/* No special structure, just free() on delete */
     }
     else
     {
-	state	= (pANTLR3_LEX_STATE)input->markers->get(input->markers, input->markDepth - 1);
+		state	= (pANTLR3_LEX_STATE)input->markers->get(input->markers, input->markDepth - 1);
 
-	/* Assume no errors for speed, it will just blow up if the table failed
-	 * for some reasons, hence lots of unit tests on the tables ;-)
-	 */
+		/* Assume no errors for speed, it will just blow up if the table failed
+		 * for some reasons, hence lots of unit tests on the tables ;-)
+		 */
     }
 
     /* We have created or retrieved the state, so update it with the current
@@ -522,6 +528,7 @@
     /* Find the supplied mark state 
      */
     state   = (pANTLR3_LEX_STATE)input->markers->get(input->markers, (ANTLR3_UINT32)(mark - 1));
+	if (state == NULL) { return; }
 
     /* Seek input pointer to the requested point (note we supply the void *pointer
      * to whatever is implementing the int stream to seek).
@@ -572,7 +579,7 @@
 	ANTLR3_INT32   count;
 	pANTLR3_INPUT_STREAM input;
 
-	input   = ANTLR3_FUNC_PTR(((pANTLR3_INPUT_STREAM) is->super));
+	input   = (pANTLR3_INPUT_STREAM)ANTLR3_FUNC_PTR(((pANTLR3_INPUT_STREAM) is->super));
 
 	/* If the requested seek point is less than the current
 	* input point, then we assume that we are resetting from a mark
@@ -865,7 +872,7 @@
         // in the input stream
         //
 	input       = ((pANTLR3_INPUT_STREAM) (is->super));
-        nextChar    = input->nextChar;
+        nextChar    = (UTF16*)input->nextChar;
 
         // If a positive offset then advance forward, else retreat
         //
@@ -1145,7 +1152,7 @@
         // in the input stream
         //
 	input       = ((pANTLR3_INPUT_STREAM) (is->super));
-        nextChar    = input->nextChar;
+        nextChar    = (pANTLR3_UCHAR)input->nextChar;
 
         // If a positive offset then advance forward, else retreat
         //
@@ -1366,7 +1373,7 @@
         // in the input stream
         //
 	input       = ((pANTLR3_INPUT_STREAM) (is->super));
-        nextChar    = input->nextChar;
+        nextChar    = (pANTLR3_UCHAR)input->nextChar;
 
         // If a positive offset then advance forward, else retreat
         //
@@ -1810,7 +1817,7 @@
 
     input   = ((pANTLR3_INPUT_STREAM) (is->super));
 
-    nextChar = input->nextChar;
+    nextChar = (pANTLR3_UINT8)input->nextChar;
 
     if	(nextChar < (((pANTLR3_UINT8)input->data) + input->sizeBuf))
     {	
@@ -1876,7 +1883,7 @@
 
     input   = ((pANTLR3_INPUT_STREAM) (is->super));
 
-    nextChar = input->nextChar;
+    nextChar = (pANTLR3_UINT8)input->nextChar;
 
     // Do we need to traverse forwards or backwards?
     // - LA(0) is treated as LA(1) and we assume that the nextChar is
diff --git a/runtime/C/src/antlr3lexer.c b/runtime/C/src/antlr3lexer.c
index d981ab7..962163d 100644
--- a/runtime/C/src/antlr3lexer.c
+++ b/runtime/C/src/antlr3lexer.c
@@ -176,7 +176,7 @@
 {
     pANTLR3_LEXER   lexer;
 
-    lexer   = rec->super;
+    lexer   = (pANTLR3_LEXER)rec->super;
 
     lexer->rec->state->token			    = NULL;
     lexer->rec->state->type			    = ANTLR3_TOKEN_INVALID;
@@ -343,12 +343,12 @@
 	// stream we just consumed, otherwise we will return EOF
 	// on the reinstalled input stream, when in actual fact
 	// there might be more input streams to POP before the
-	// real EOF of the whole logical inptu stream. Hence we
-	// use a while loop here until we find somethign in the stream
+	// real EOF of the whole logical input stream. Hence we
+	// use a while loop here until we find something in the stream
 	// that isn't EOF or we reach the actual end of the last input
 	// stream on the stack.
 	//
-	while	(tok->type == ANTLR3_TOKEN_EOF)
+	while	((tok != NULL) && (tok->type == ANTLR3_TOKEN_EOF))
 	{
 		pANTLR3_LEXER   lexer;
 
@@ -649,6 +649,7 @@
     * trying to emit a new token.
     */
     token   = lexer->rec->state->tokFactory->newToken(lexer->rec->state->tokFactory);
+	if (token == NULL) { return NULL; }
 
     /* Install the supplied information, and some other bits we already know
     * get added automatically, such as the input stream it is associated with
diff --git a/runtime/C/src/antlr3rewritestreams.c b/runtime/C/src/antlr3rewritestreams.c
index 9afb6e1..8da3011 100644
--- a/runtime/C/src/antlr3rewritestreams.c
+++ b/runtime/C/src/antlr3rewritestreams.c
@@ -197,7 +197,7 @@
 		// Remove the entry from the vector. We do not
 		// cause it to be freed by using remove.
 		//
-		stream = rec->state->rStreams->remove(rec->state->rStreams, rec->state->rStreams->count - 1);
+		stream = (pANTLR3_REWRITE_RULE_ELEMENT_STREAM)rec->state->rStreams->remove(rec->state->rStreams, rec->state->rStreams->count - 1);
 
 		// We found a stream we can reuse.
 		// If the stream had a vector, then it will have been cleared
@@ -577,13 +577,13 @@
 		// if out of elements and size is 1, dup
 		//
 		el = stream->_next(stream);
-		return stream->dup(stream, el);
+		return (pANTLR3_BASE_TREE)stream->dup(stream, el);
 	}
 
 	// test size above then fetch
 	//
 	el = stream->_next(stream);
-	return el;
+	return (pANTLR3_BASE_TREE)el;
 }
 
 /// Return the next element for a caller that wants just the token
@@ -607,7 +607,7 @@
 	{
 		pANTLR3_BASE_TREE el;
 
-		el = stream->_next(stream);
+		el = (pANTLR3_BASE_TREE)stream->_next(stream);
 
 		return	stream->dup(stream, el);
 	}
@@ -737,7 +737,7 @@
 static pANTLR3_BASE_TREE	
 toTreeNode   (pANTLR3_REWRITE_RULE_ELEMENT_STREAM stream, void * element)
 {
-	return stream->adaptor->dupNode(stream->adaptor, (pANTLR3_BASE_TREE)element);
+	return (pANTLR3_BASE_TREE)stream->adaptor->dupNode(stream->adaptor, (pANTLR3_BASE_TREE)element);
 }
 
 #ifdef ANTLR3_WINDOWS
@@ -766,13 +766,13 @@
 static pANTLR3_BASE_TREE
 nextNodeToken(pANTLR3_REWRITE_RULE_ELEMENT_STREAM stream)
 {
-	return stream->adaptor->create(stream->adaptor, stream->_next(stream));
+	return (pANTLR3_BASE_TREE)stream->adaptor->create(stream->adaptor, (pANTLR3_COMMON_TOKEN)stream->_next(stream));
 }
 
 static pANTLR3_BASE_TREE
 nextNodeNode(pANTLR3_REWRITE_RULE_ELEMENT_STREAM stream)
 {
-	return stream->_next(stream);
+	return (pANTLR3_BASE_TREE)stream->_next(stream);
 }
 
 /// Treat next element as a single node even if it's a subtree.
@@ -789,7 +789,7 @@
 {
 
 	ANTLR3_UINT32	n;
-	pANTLR3_BASE_TREE	el = stream->_next(stream);
+	pANTLR3_BASE_TREE	el = (pANTLR3_BASE_TREE)stream->_next(stream);
 
 	n = stream->size(stream);
 	if (stream->dirty == ANTLR3_TRUE || (stream->cursor > n && n == 1))
@@ -797,7 +797,7 @@
 		// We are out of elements and the size is 1, which means we just 
 		// dup the node that we have
 		//
-		return	stream->adaptor->dupNode(stream->adaptor, el);
+		return	(pANTLR3_BASE_TREE)stream->adaptor->dupNode(stream->adaptor, el);
 	}
 
 	// We were not out of nodes, so the one we received is the one to return
@@ -837,7 +837,7 @@
 {
 	if (stream->elementDescription == NULL)
 	{
-		stream->elementDescription = "<unknown source>";
+		stream->elementDescription = (void*)"<unknown source>";
 	}
 
 	return  stream->elementDescription;
diff --git a/runtime/C/src/antlr3string.c b/runtime/C/src/antlr3string.c
index b29c020..36d0de0 100644
--- a/runtime/C/src/antlr3string.c
+++ b/runtime/C/src/antlr3string.c
@@ -432,9 +432,11 @@
     /* Always add one more byte for a terminator ;-)
     */
     string->chars	= (pANTLR3_UINT8) ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_UINT8) * (size+1)));
-    *(string->chars)	= '\0';
-    string->size	= size + 1;
-
+	if (string->chars != NULL)
+    {
+		*(string->chars)	= '\0';
+		string->size	= size + 1;
+	}
 
     return string;
 }
@@ -460,8 +462,11 @@
     /* Always add one more byte for a terminator ;-)
     */	
     string->chars	= (pANTLR3_UINT8) ANTLR3_MALLOC((size_t)(sizeof(ANTLR3_UINT16) * (size+1)));
-    *(string->chars)	= '\0';
-    string->size	= size+1;	/* Size is always in characters, as is len */
+    if (string->chars != NULL)
+	{
+		*(string->chars)	= '\0';
+		string->size	= size+1;	/* Size is always in characters, as is len */
+	}
 
     return string;
 }
@@ -800,7 +805,12 @@
 
     if	(string->size < (string->len + len + 1))
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + len + 1));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + len + 1));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + len + 1;
     }
 
@@ -823,7 +833,12 @@
 
     if	(string->size < (string->len + len + 1))
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)((sizeof(ANTLR3_UINT16)*(string->len + len + 1))));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)((sizeof(ANTLR3_UINT16)*(string->len + len + 1))));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + len + 1;
     }
 
@@ -857,7 +872,12 @@
 
     if	(string->size < (string->len + len + 1))
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)( sizeof(ANTLR3_UINT16) *(string->len + len + 1) ));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)( sizeof(ANTLR3_UINT16) *(string->len + len + 1) ));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + len + 1;
     }
 
@@ -877,7 +897,12 @@
     len = (ANTLR3_UINT32)strlen(chars);
     if	(string->size < len + 1)
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(len + 1));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(len + 1));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= len + 1;
     }
 
@@ -900,7 +925,12 @@
     len = (ANTLR3_UINT32)strlen(chars);
     if	(string->size < len + 1)
 	{
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(len + 1)));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(len + 1)));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= len + 1;
     }
     apPoint = ((pANTLR3_UINT16)string->chars);
@@ -933,7 +963,12 @@
 
     if	(string->size < len + 1)
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(len + 1)));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(len + 1)));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= len + 1;
     }
 
@@ -951,7 +986,12 @@
 {
     if	(string->size < string->len + 2)
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + 2));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + 2));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + 2;
     }
     *(string->chars + string->len)	= (ANTLR3_UINT8)c;
@@ -968,7 +1008,12 @@
 
     if	(string->size < string->len + 2)
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16) * (string->len + 2)));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16) * (string->len + 2)));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + 2;
     }
     ptr	= (pANTLR3_UINT16)(string->chars);
@@ -1035,7 +1080,12 @@
 
     if	(string->size < (string->len + len + 1))
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + len + 1));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(string->len + len + 1));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + len + 1;
     }
 
@@ -1073,8 +1123,13 @@
 
     if	(string->size < (string->len + len + 1))
     {
-	string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(string->len + len + 1)));
-	string->size	= string->len + len + 1;
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(string->len + len + 1)));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
+		string->size	= string->len + len + 1;
     }
 
     /* Move the characters we are inserting before, including the delimiter
@@ -1120,7 +1175,12 @@
 
     if	(string->size < (string->len + len + 1))
     {
-		string->chars	= (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(string->len + len + 1)));
+		pANTLR3_UINT8 newAlloc = (pANTLR3_UINT8) ANTLR3_REALLOC((void *)string->chars, (ANTLR3_UINT32)(sizeof(ANTLR3_UINT16)*(string->len + len + 1)));
+		if (newAlloc == NULL)
+		{
+			return NULL;
+		}
+		string->chars	= newAlloc;
 		string->size	= string->len + len + 1;
     }
 
@@ -1379,24 +1439,27 @@
 	/* Always add one more byte for a terminator
 	*/
 	newStr->chars   = (pANTLR3_UINT8) ANTLR3_MALLOC((size_t)(string->len + 1));
-	newStr->size    = string->len + 1;
-	newStr->len	    = string->len;
-
-	/* Now copy each UTF16 charActer , making it an 8 bit character of 
-	* some sort.
-	*/
-	for	(i=0; i<string->len; i++)
+	if (newStr->chars != NULL)
 	{
-		ANTLR3_UCHAR	c;
+		newStr->size    = string->len + 1;
+		newStr->len	    = string->len;
 
-		c = *(((pANTLR3_UINT16)(string->chars)) + i);
+		/* Now copy each UTF16 charActer , making it an 8 bit character of 
+		* some sort.
+		*/
+		for	(i=0; i<string->len; i++)
+		{
+			ANTLR3_UCHAR	c;
 
-		*(newStr->chars + i) = (ANTLR3_UINT8)(c > 255 ? '_' : c);
+			c = *(((pANTLR3_UINT16)(string->chars)) + i);
+
+			*(newStr->chars + i) = (ANTLR3_UINT8)(c > 255 ? '_' : c);
+		}
+
+		/* Terminate
+		*/
+		*(newStr->chars + newStr->len) = '\0';
 	}
 
-	/* Terminate
-	*/
-	*(newStr->chars + newStr->len) = '\0';
-
 	return newStr;
 }
diff --git a/runtime/C/src/antlr3treeparser.c b/runtime/C/src/antlr3treeparser.c
index b7e035a..c40a1ef 100644
--- a/runtime/C/src/antlr3treeparser.c
+++ b/runtime/C/src/antlr3treeparser.c
@@ -232,7 +232,7 @@
 		current = tns->_LT(tns, i--);
     }
 
-	node	= current->dupNode(current);
+	node	= (pANTLR3_BASE_TREE)current->dupNode(current);
 
 	// Find the newly dupicated token
 	//
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj
index 5ca19d8..9c52017 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj
@@ -12,15 +12,8 @@
     <AssemblyName>Antlr3.Runtime.Debug</AssemblyName>
     <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
-    <SccProjectName>Perforce Project</SccProjectName>
-    <SccLocalPath>..\..\..\..\..\..</SccLocalPath>
-    <SccAuxPath>
-    </SccAuxPath>
-    <SccProvider>MSSCCI:Perforce SCM</SccProvider>
     <SignAssembly>true</SignAssembly>
-    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
-    <TargetFrameworkProfile>
-    </TargetFrameworkProfile>
+    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
@@ -30,6 +23,7 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Debug\Antlr3.Runtime.Debug.xml</DocumentationFile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -38,6 +32,7 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Release\Antlr3.Runtime.Debug.xml</DocumentationFile>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="System" />
@@ -56,7 +51,7 @@
     <Compile Include="JavaExtensions\ExceptionExtensions.cs" />
     <Compile Include="Misc\DoubleKeyMap`3.cs" />
     <Compile Include="Misc\Stats.cs" />
-    <None Include="..\..\..\..\..\..\..\keys\antlr\Key.snk">
+    <None Include="..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk">
       <Link>Key.snk</Link>
     </None>
     <None Include="ParserDebugger.cs" />
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/ParseTreeBuilder.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/ParseTreeBuilder.cs
index deeaf3b..cb5f678 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/ParseTreeBuilder.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/ParseTreeBuilder.cs
@@ -58,7 +58,8 @@
         {
             get
             {
-                return callStack.Peek();
+                ParseTree[] stack = callStack.ToArray();
+                return stack[stack.Length - 1];
             }
         }
 
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs
index b8c988f..038cddb 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs
@@ -40,9 +40,9 @@
 [assembly: AssemblyTitle( "Antlr3.Runtime.Debug" )]
 [assembly: AssemblyDescription( "" )]
 [assembly: AssemblyConfiguration( "" )]
-[assembly: AssemblyCompany( "Pixel Mine, Inc." )]
+[assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )]
 [assembly: AssemblyProduct( "Antlr3.Runtime.Debug" )]
-[assembly: AssemblyCopyright( "Copyright © Pixel Mine 2010" )]
+[assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )]
 [assembly: AssemblyTrademark( "" )]
 [assembly: AssemblyCulture( "" )]
 [assembly: CLSCompliant( true )]
@@ -66,5 +66,5 @@
  *      the Major or Minor version is incremented.
  *   3. Revision is the Perforce changelist number associated with the release.
  */
-[assembly: AssemblyVersion("3.3.4.8517")]
-[assembly: AssemblyFileVersion("3.3.4.8517")]
+[assembly: AssemblyVersion("3.5.0.2")]
+[assembly: AssemblyFileVersion("3.5.0.2")]
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj
index 959a9f9..2c90504 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj
@@ -12,10 +12,6 @@
     <AssemblyName>Antlr3.Runtime.JavaExtensions</AssemblyName>
     <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
-    <SccProjectName>SAK</SccProjectName>
-    <SccLocalPath>SAK</SccLocalPath>
-    <SccAuxPath>SAK</SccAuxPath>
-    <SccProvider>SAK</SccProvider>
     <TargetFrameworkProfile>Client</TargetFrameworkProfile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@@ -39,7 +35,7 @@
     <SignAssembly>true</SignAssembly>
   </PropertyGroup>
   <PropertyGroup>
-    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
+    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="System" />
@@ -80,7 +76,7 @@
     </ProjectReference>
   </ItemGroup>
   <ItemGroup>
-    <None Include="..\..\..\..\..\..\..\keys\antlr\Key.snk">
+    <None Include="..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk">
       <Link>Key.snk</Link>
     </None>
   </ItemGroup>
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs
index 8aa2671..00e66a9 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs
@@ -40,9 +40,9 @@
 [assembly: AssemblyTitle( "Antlr3.Runtime.JavaExtensions" )]
 [assembly: AssemblyDescription( "" )]
 [assembly: AssemblyConfiguration( "" )]
-[assembly: AssemblyCompany( "Pixel Mine, Inc." )]
+[assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )]
 [assembly: AssemblyProduct( "Antlr3.Runtime.JavaExtensions" )]
-[assembly: AssemblyCopyright( "Copyright © Pixel Mine 2010" )]
+[assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )]
 [assembly: AssemblyTrademark( "" )]
 [assembly: AssemblyCulture( "" )]
 [assembly: CLSCompliant( true )]
@@ -64,7 +64,6 @@
  *   2. Build is incremented each time the C# port is packaged for release (regardless
  *      of whether it's an incremental or nightly). The value resets to zero whenever
  *      the Major or Minor version is incremented.
- *   3. Revision is the Perforce changelist number associated with the release.
  */
-[assembly: AssemblyVersion("3.3.4.8517")]
-[assembly: AssemblyFileVersion("3.3.4.8517")]
+[assembly: AssemblyVersion("3.5.0.2")]
+[assembly: AssemblyFileVersion("3.5.0.2")]
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/StringExtensions.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/StringExtensions.cs
index 8432512..837908a 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/StringExtensions.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/StringExtensions.cs
@@ -30,6 +30,7 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#if DEBUG
 namespace Antlr.Runtime.JavaExtensions
 {
     using ObsoleteAttribute = System.ObsoleteAttribute;
@@ -38,7 +39,6 @@
 
     public static class StringExtensions
     {
-#if DEBUG
         [Obsolete]
         public static char charAt( this string str, int index )
         {
@@ -98,19 +98,19 @@
         {
             return str.Replace(oldValue, newValue);
         }
-#endif
 
+        [Obsolete]
         public static string replaceAll( this string str, string regex, string newValue )
         {
             return Regex.Replace( str, regex, newValue );
         }
 
+        [Obsolete]
         public static string replaceFirst( this string str, string regex, string replacement )
         {
             return Regex.Replace( str, regex, replacement );
         }
 
-#if DEBUG
         [Obsolete]
         public static bool startsWith( this string str, string value )
         {
@@ -146,6 +146,6 @@
         {
             return str.Trim();
         }
-#endif
     }
 }
+#endif
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj
index 11206dc..75c4cac 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj
@@ -13,10 +13,6 @@
     <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
     <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
-    <SccProjectName>SAK</SccProjectName>
-    <SccLocalPath>SAK</SccLocalPath>
-    <SccAuxPath>SAK</SccAuxPath>
-    <SccProvider>SAK</SccProvider>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
@@ -41,14 +37,10 @@
     <Reference Include="System.Core">
       <RequiredTargetFramework>3.5</RequiredTargetFramework>
     </Reference>
-    <Reference Include="vjslib" />
+    <Reference Include="System.Numerics" />
   </ItemGroup>
   <ItemGroup>
-    <Compile Include="Composition\Program.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\..\..\..\..\..\antlrcs\main\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj">
+    <ProjectReference Include="..\..\..\..\..\..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj">
       <Project>{B5910BE2-DE21-4AA9-95C1-486F42B9E794}</Project>
       <Name>Antlr3.StringTemplate</Name>
     </ProjectReference>
@@ -66,11 +58,37 @@
     </ProjectReference>
   </ItemGroup>
   <ItemGroup>
-    <Antlr3 Include="SimpleExpression.g3">
-      <Generator>MSBuild:Compile</Generator>
+    <Antlr3 Include="SimpleExpression.g3" />
+    <Antlr3 Include="FastSimpleExpression.g3" />
+    <None Include="JavaCompat\Expr.g3" />
+    <Antlr3 Include="BuildOptions\DebugGrammar.g3">
+      <!--<GrammarOptions>-debug</GrammarOptions>-->
     </Antlr3>
+    <Antlr3 Include="BuildOptions\DebugTreeGrammar.g3">
+      <!--<GrammarOptions>-debug</GrammarOptions>-->
+    </Antlr3>
+    <Antlr3 Include="StringTemplateOutput.g3" />
+    <Antlr3 Include="TestActionFeatures.g3" />
+    <Antlr3 Include="SemanticPredicateReduction.g3" />
+    <Antlr3 Include="Composition\Reduce.g3" />
+    <Antlr3 Include="Composition\Simplify.g3" />
+    <Antlr3 Include="Composition\VecMath.g3" />
+    <AntlrAbstractGrammar Include="Composition\VecMath_Lexer.g3">
+      <Generator>MSBuild:Compile</Generator>
+    </AntlrAbstractGrammar>
+    <AntlrAbstractGrammar Include="Composition\VecMath_Parser.g3">
+      <Generator>MSBuild:Compile</Generator>
+    </AntlrAbstractGrammar>
+    <Antlr3 Include="PreprocessorLexer.g3" />
+    <Antlr3 Include="SynpredTreeParser.g3" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="Composition\Program.cs" />
+    <Compile Include="PreprocessorLexer.g3.cs">
+      <DependentUpon>PreprocessorLexer.g3</DependentUpon>
+    </Compile>
+    <Compile Include="PreprocessorTests.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="SemanticPredicateReduction.g3.lexer.cs">
       <DependentUpon>SemanticPredicateReduction.g3</DependentUpon>
     </Compile>
@@ -83,40 +101,18 @@
     <Compile Include="SimpleExpressionParserHelper.cs">
       <DependentUpon>SimpleExpression.g3</DependentUpon>
     </Compile>
-  </ItemGroup>
-  <ItemGroup>
-    <Antlr3 Include="FastSimpleExpression.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
     <Compile Include="FastSimpleExpressionLexerHelper.cs">
       <DependentUpon>FastSimpleExpression.g3</DependentUpon>
     </Compile>
     <Compile Include="FastSimpleExpressionParserHelper.cs">
       <DependentUpon>FastSimpleExpression.g3</DependentUpon>
     </Compile>
-  </ItemGroup>
-  <ItemGroup>
-    <Antlr3 Include="JavaCompat\Expr.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
-  </ItemGroup>
-  <ItemGroup>
-    <Antlr3 Include="BuildOptions\DebugGrammar.g3">
-      <!--<GrammarOptions>-debug</GrammarOptions>-->
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
     <Compile Include="BuildOptions\DebugGrammarLexerHelper.cs">
       <DependentUpon>DebugGrammar.g3</DependentUpon>
     </Compile>
     <Compile Include="BuildOptions\DebugGrammarParserHelper.cs">
       <DependentUpon>DebugGrammar.g3</DependentUpon>
     </Compile>
-  </ItemGroup>
-  <ItemGroup>
-    <Antlr3 Include="BuildOptions\DebugTreeGrammar.g3">
-      <!--<GrammarOptions>-debug</GrammarOptions>-->
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
     <Compile Include="BuildOptions\DebugTreeGrammarHelper.cs">
       <DependentUpon>DebugTreeGrammar.g3</DependentUpon>
     </Compile>
@@ -135,6 +131,9 @@
     <Compile Include="StringTemplateOutput.g3.parser.cs">
       <DependentUpon>StringTemplateOutput.g3</DependentUpon>
     </Compile>
+    <Compile Include="SynpredTreeParser.g3.cs">
+      <DependentUpon>SynpredTreeParser.g3</DependentUpon>
+    </Compile>
     <Compile Include="TestActionFeatures.g3.lexer.cs">
       <DependentUpon>TestActionFeatures.g3</DependentUpon>
     </Compile>
@@ -153,7 +152,6 @@
   <ItemGroup>
     <None Include="BuildOptions\ProfileGrammar.g3">
       <!--<GrammarOptions>-profile</GrammarOptions>-->
-      <Generator>MSBuild:Compile</Generator>
     </None>
     <None Include="BuildOptions\ProfileGrammarLexerHelper.cs">
       <DependentUpon>ProfileGrammar.g3</DependentUpon>
@@ -161,41 +159,24 @@
     <None Include="BuildOptions\ProfileGrammarParserHelper.cs">
       <DependentUpon>ProfileGrammar.g3</DependentUpon>
     </None>
-    <Antlr3 Include="StringTemplateOutput.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
-    <Antlr3 Include="TestActionFeatures.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
-    <Antlr3 Include="SemanticPredicateReduction.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </Antlr3>
-    <Antlr3 Include="Composition\Reduce.g3" />
-    <Antlr3 Include="Composition\Simplify.g3" />
-    <Antlr3 Include="Composition\VecMath.g3" />
-    <None Include="Composition\VecMath_Lexer.g3" />
-    <None Include="Composition\VecMath_Parser.g3" />
-    <None Include="TestExpressionFeatures.g3">
-      <Generator>MSBuild:Compile</Generator>
-    </None>
+    <None Include="TestExpressionFeatures.g3" />
   </ItemGroup>
   <ItemGroup>
     <None Include="BuildOptions\ProfileTreeGrammar.g3">
       <!--<GrammarOptions>-profile</GrammarOptions>-->
-      <Generator>MSBuild:Compile</Generator>
     </None>
     <None Include="BuildOptions\ProfileTreeGrammarHelper.cs">
       <DependentUpon>ProfileTreeGrammar.g3</DependentUpon>
     </None>
   </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <PropertyGroup>
     <!-- Folder containing AntlrBuildTask.dll -->
-    <AntlrBuildTaskPath>$(SolutionDir)bin\Bootstrap</AntlrBuildTaskPath>
+    <AntlrBuildTaskPath>$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap</AntlrBuildTaskPath>
     <!-- Path to the ANTLR Tool itself. -->
-    <AntlrToolPath>$(SolutionDir)bin\Bootstrap\Antlr3.exe</AntlrToolPath>
+    <AntlrToolPath>$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap\Antlr3.exe</AntlrToolPath>
   </PropertyGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <Import Project="$(ProjectDir)..\..\..\..\..\..\antlrcs\main\bin\Bootstrap\Antlr3.targets" />
+  <Import Project="$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap\Antlr3.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
        Other similar extension points exist, see Microsoft.Common.targets.
   <Target Name="BeforeBuild">
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammar.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammar.g3
index 36b1884..6edb6d3 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammar.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammar.g3
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -46,6 +46,9 @@
 	CALL;
 }
 
+@lexer::namespace{Antlr3.Runtime.Test.BuildOptions}
+@parser::namespace{Antlr3.Runtime.Test.BuildOptions}
+
 // START:stat
 prog: ( stat )*
     ;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammarParserHelper.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammarParserHelper.cs
index 95beb20..638100e 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammarParserHelper.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugGrammarParserHelper.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -30,11 +30,14 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-using System.Collections.Generic;
-using Antlr.Runtime.Tree;
-
-partial class DebugGrammarParser
+namespace Antlr3.Runtime.Test.BuildOptions
 {
-    /** List of function definitions. Must point at the FUNC nodes. */
-    List<CommonTree> functionDefinitions = new List<CommonTree>();
+    using System.Collections.Generic;
+    using Antlr.Runtime.Tree;
+
+    partial class DebugGrammarParser
+    {
+        /** List of function definitions. Must point at the FUNC nodes. */
+        List<CommonTree> functionDefinitions = new List<CommonTree>();
+    }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammar.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammar.g3
index b16a73e..40ee359 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammar.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammar.g3
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -44,11 +44,13 @@
 {
 //import java.util.Map;
 //import java.util.HashMap;
-using BigInteger = java.math.BigInteger;
+using BigInteger = System.Numerics.BigInteger;
 using Console = System.Console;
 }
 // END:members
 
+@namespace{Antlr3.Runtime.Test.BuildOptions}
+
 // START:rules
 prog:   stat*
     ;
@@ -61,13 +63,13 @@
     ;
 
 expr returns [BigInteger value]
-    :   ^('+' a=expr b=expr)       { $value = $a.value.add($b.value); }
-    |   ^('-' a=expr b=expr)       { $value = $a.value.subtract($b.value); }
-    |   ^('*' a=expr b=expr)       { $value = $a.value.multiply($b.value); }
-    |   ^('/' a=expr b=expr)       { $value = $a.value.divide($b.value); }
-    |   ^('%' a=expr b=expr)       { $value = $a.value.remainder($b.value); }
+    :   ^('+' a=expr b=expr)       { $value = $a.value + $b.value; }
+    |   ^('-' a=expr b=expr)       { $value = $a.value - $b.value; }
+    |   ^('*' a=expr b=expr)       { $value = $a.value * $b.value; }
+    |   ^('/' a=expr b=expr)       { $value = $a.value / $b.value; }
+    |   ^('%' a=expr b=expr)       { $value = $a.value \% $b.value; }
     |   ID                         { $value = getValue($ID.text); }
-    |   INT                        { $value = new BigInteger($INT.text); }
+    |   INT                        { $value = BigInteger.Parse($INT.text); }
     |   call                       { $value = $call.value; }
     ;
 
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammarHelper.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammarHelper.cs
index af83214..c139aff 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammarHelper.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/DebugTreeGrammarHelper.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -30,87 +30,90 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-using System.Collections.Generic;
-using Antlr.Runtime.Tree;
-
-using BigInteger = java.math.BigInteger;
-using Console = System.Console;
-
-partial class DebugTreeGrammar
+namespace Antlr3.Runtime.Test.BuildOptions
 {
-    /** Points to functions tracked by tree builder. */
-    private List<CommonTree> functionDefinitions;
+    using System.Collections.Generic;
+    using Antlr.Runtime.Tree;
 
-    /** Remember local variables. Currently, this is only the function parameter.
-     */
-    private readonly IDictionary<string, BigInteger> localMemory = new Dictionary<string, BigInteger>();
+    using BigInteger = System.Numerics.BigInteger;
+    using Console = System.Console;
 
-    /** Remember global variables set by =. */
-    private IDictionary<string, BigInteger> globalMemory = new Dictionary<string, BigInteger>();
-
-    /** Set up an evaluator with a node stream; and a set of function definition ASTs. */
-    public DebugTreeGrammar( CommonTreeNodeStream nodes, List<CommonTree> functionDefinitions )
-        : this( nodes )
+    partial class DebugTreeGrammar
     {
-        this.functionDefinitions = functionDefinitions;
-    }
+        /** Points to functions tracked by tree builder. */
+        private List<CommonTree> functionDefinitions;
 
-    /** Set up a local evaluator for a nested function call. The evaluator gets the definition
-     *  tree of the function; the set of all defined functions (to find locally called ones); a
-     *  pointer to the global variable memory; and the value of the function parameter to be
-     *  added to the local memory.
-     */
-    private DebugTreeGrammar( CommonTree function,
-                 List<CommonTree> functionDefinitions,
-                 IDictionary<string, BigInteger> globalMemory,
-                 BigInteger paramValue )
-        // Expected tree for function: ^(FUNC ID ( INT | ID ) expr)
-        : this( new CommonTreeNodeStream( function.GetChild( 2 ) ), functionDefinitions )
-    {
-        this.globalMemory = globalMemory;
-        localMemory[function.GetChild( 1 ).Text] = paramValue;
-    }
+        /** Remember local variables. Currently, this is only the function parameter.
+         */
+        private readonly IDictionary<string, BigInteger> localMemory = new Dictionary<string, BigInteger>();
 
-    /** Find matching function definition for a function name and parameter
-     *  value. The first definition is returned where (a) the name matches
-     *  and (b) the formal parameter agrees if it is defined as constant.
-     */
-    private CommonTree findFunction( string name, BigInteger paramValue )
-    {
-        foreach ( CommonTree f in functionDefinitions )
+        /** Remember global variables set by =. */
+        private IDictionary<string, BigInteger> globalMemory = new Dictionary<string, BigInteger>();
+
+        /** Set up an evaluator with a node stream; and a set of function definition ASTs. */
+        public DebugTreeGrammar(CommonTreeNodeStream nodes, List<CommonTree> functionDefinitions)
+            : this(nodes)
         {
-            // Expected tree for f: ^(FUNC ID (ID | INT) expr)
-            if ( f.GetChild( 0 ).Text.Equals( name ) )
+            this.functionDefinitions = functionDefinitions;
+        }
+
+        /** Set up a local evaluator for a nested function call. The evaluator gets the definition
+         *  tree of the function; the set of all defined functions (to find locally called ones); a
+         *  pointer to the global variable memory; and the value of the function parameter to be
+         *  added to the local memory.
+         */
+        private DebugTreeGrammar(CommonTree function,
+                     List<CommonTree> functionDefinitions,
+                     IDictionary<string, BigInteger> globalMemory,
+                     BigInteger paramValue)
+            // Expected tree for function: ^(FUNC ID ( INT | ID ) expr)
+            : this(new CommonTreeNodeStream(function.GetChild(2)), functionDefinitions)
+        {
+            this.globalMemory = globalMemory;
+            localMemory[function.GetChild(1).Text] = paramValue;
+        }
+
+        /** Find matching function definition for a function name and parameter
+         *  value. The first definition is returned where (a) the name matches
+         *  and (b) the formal parameter agrees if it is defined as constant.
+         */
+        private CommonTree findFunction(string name, BigInteger paramValue)
+        {
+            foreach (CommonTree f in functionDefinitions)
             {
-                // Check whether parameter matches
-                CommonTree formalPar = (CommonTree)f.GetChild( 1 );
-                if ( formalPar.Token.Type == INT
-                    && !new BigInteger( formalPar.Token.Text ).Equals( paramValue ) )
+                // Expected tree for f: ^(FUNC ID (ID | INT) expr)
+                if (f.GetChild(0).Text.Equals(name))
                 {
-                    // Constant in formalPar list does not match actual value -> no match.
-                    continue;
+                    // Check whether parameter matches
+                    CommonTree formalPar = (CommonTree)f.GetChild(1);
+                    if (formalPar.Token.Type == INT
+                        && !BigInteger.Parse(formalPar.Token.Text).Equals(paramValue))
+                    {
+                        // Constant in formalPar list does not match actual value -> no match.
+                        continue;
+                    }
+                    // Parameter (value for INT formal arg) as well as fct name agrees!
+                    return f;
                 }
-                // Parameter (value for INT formal arg) as well as fct name agrees!
-                return f;
             }
+            return null;
         }
-        return null;
-    }
 
-    /** Get value of name up call stack. */
-    internal BigInteger getValue( string name )
-    {
-        BigInteger value;
-        if ( localMemory.TryGetValue( name, out value ) && value != null )
+        /** Get value of name up call stack. */
+        internal BigInteger getValue(string name)
         {
-            return value;
+            BigInteger value;
+            if (localMemory.TryGetValue(name, out value) && value != null)
+            {
+                return value;
+            }
+            if (globalMemory.TryGetValue(name, out value) && value != null)
+            {
+                return value;
+            }
+            // not found in local memory or global memory
+            Console.Error.WriteLine("undefined variable " + name);
+            return BigInteger.Zero;
         }
-        if ( globalMemory.TryGetValue( name, out value ) && value != null )
-        {
-            return value;
-        }
-        // not found in local memory or global memory
-        Console.Error.WriteLine( "undefined variable " + name );
-        return new BigInteger( "0" );
     }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammar.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammar.g3
index 5f8de16..9230134 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammar.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammar.g3
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -46,6 +46,9 @@
 	CALL;
 }
 
+@lexer::namespace{Antlr3.Runtime.Test.BuildOptions}
+@parser::namespace{Antlr3.Runtime.Test.BuildOptions}
+
 // START:stat
 prog: ( stat )*
     ;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammarParserHelper.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammarParserHelper.cs
index ddd7533..205a088 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammarParserHelper.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileGrammarParserHelper.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -30,11 +30,14 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-using System.Collections.Generic;
-using Antlr.Runtime.Tree;
-
-partial class ProfileGrammarParser
+namespace Antlr3.Runtime.Test.BuildOptions
 {
-    /** List of function definitions. Must point at the FUNC nodes. */
-    List<CommonTree> functionDefinitions = new List<CommonTree>();
+    using System.Collections.Generic;
+    using Antlr.Runtime.Tree;
+
+    partial class ProfileGrammarParser
+    {
+        /** List of function definitions. Must point at the FUNC nodes. */
+        List<CommonTree> functionDefinitions = new List<CommonTree>();
+    }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammar.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammar.g3
index f6786db..5bf107b 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammar.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammar.g3
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -49,6 +49,8 @@
 }
 // END:members
 
+@namespace{Antlr3.Runtime.Test.BuildOptions}
+
 // START:rules
 prog:   stat*
     ;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammarHelper.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammarHelper.cs
index 47cc8a8..06d678a 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammarHelper.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/BuildOptions/ProfileTreeGrammarHelper.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -30,87 +30,90 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-using System.Collections.Generic;
-using Antlr.Runtime.Tree;
-
-using BigInteger = java.math.BigInteger;
-using Console = System.Console;
-
-partial class ProfileTreeGrammar
+namespace Antlr3.Runtime.Test.BuildOptions
 {
-    /** Points to functions tracked by tree builder. */
-    private List<CommonTree> functionDefinitions;
+    using System.Collections.Generic;
+    using Antlr.Runtime.Tree;
 
-    /** Remember local variables. Currently, this is only the function parameter.
-     */
-    private readonly IDictionary<string, BigInteger> localMemory = new Dictionary<string, BigInteger>();
+    using BigInteger = java.math.BigInteger;
+    using Console = System.Console;
 
-    /** Remember global variables set by =. */
-    private IDictionary<string, BigInteger> globalMemory = new Dictionary<string, BigInteger>();
-
-    /** Set up an evaluator with a node stream; and a set of function definition ASTs. */
-    public ProfileTreeGrammar( CommonTreeNodeStream nodes, List<CommonTree> functionDefinitions )
-        : this( nodes )
+    partial class ProfileTreeGrammar
     {
-        this.functionDefinitions = functionDefinitions;
-    }
+        /** Points to functions tracked by tree builder. */
+        private List<CommonTree> functionDefinitions;
 
-    /** Set up a local evaluator for a nested function call. The evaluator gets the definition
-     *  tree of the function; the set of all defined functions (to find locally called ones); a
-     *  pointer to the global variable memory; and the value of the function parameter to be
-     *  added to the local memory.
-     */
-    private ProfileTreeGrammar( CommonTree function,
-                 List<CommonTree> functionDefinitions,
-                 IDictionary<string, BigInteger> globalMemory,
-                 BigInteger paramValue )
-        // Expected tree for function: ^(FUNC ID ( INT | ID ) expr)
-        : this( new CommonTreeNodeStream( function.GetChild( 2 ) ), functionDefinitions )
-    {
-        this.globalMemory = globalMemory;
-        localMemory[function.GetChild( 1 ).Text] = paramValue;
-    }
+        /** Remember local variables. Currently, this is only the function parameter.
+         */
+        private readonly IDictionary<string, BigInteger> localMemory = new Dictionary<string, BigInteger>();
 
-    /** Find matching function definition for a function name and parameter
-     *  value. The first definition is returned where (a) the name matches
-     *  and (b) the formal parameter agrees if it is defined as constant.
-     */
-    private CommonTree findFunction( string name, BigInteger paramValue )
-    {
-        foreach ( CommonTree f in functionDefinitions )
+        /** Remember global variables set by =. */
+        private IDictionary<string, BigInteger> globalMemory = new Dictionary<string, BigInteger>();
+
+        /** Set up an evaluator with a node stream; and a set of function definition ASTs. */
+        public ProfileTreeGrammar(CommonTreeNodeStream nodes, List<CommonTree> functionDefinitions)
+            : this(nodes)
         {
-            // Expected tree for f: ^(FUNC ID (ID | INT) expr)
-            if ( f.GetChild( 0 ).Text.Equals( name ) )
+            this.functionDefinitions = functionDefinitions;
+        }
+
+        /** Set up a local evaluator for a nested function call. The evaluator gets the definition
+         *  tree of the function; the set of all defined functions (to find locally called ones); a
+         *  pointer to the global variable memory; and the value of the function parameter to be
+         *  added to the local memory.
+         */
+        private ProfileTreeGrammar(CommonTree function,
+                     List<CommonTree> functionDefinitions,
+                     IDictionary<string, BigInteger> globalMemory,
+                     BigInteger paramValue)
+            // Expected tree for function: ^(FUNC ID ( INT | ID ) expr)
+            : this(new CommonTreeNodeStream(function.GetChild(2)), functionDefinitions)
+        {
+            this.globalMemory = globalMemory;
+            localMemory[function.GetChild(1).Text] = paramValue;
+        }
+
+        /** Find matching function definition for a function name and parameter
+         *  value. The first definition is returned where (a) the name matches
+         *  and (b) the formal parameter agrees if it is defined as constant.
+         */
+        private CommonTree findFunction(string name, BigInteger paramValue)
+        {
+            foreach (CommonTree f in functionDefinitions)
             {
-                // Check whether parameter matches
-                CommonTree formalPar = (CommonTree)f.GetChild( 1 );
-                if ( formalPar.Token.Type == INT
-                    && !new BigInteger( formalPar.Token.Text ).Equals( paramValue ) )
+                // Expected tree for f: ^(FUNC ID (ID | INT) expr)
+                if (f.GetChild(0).Text.Equals(name))
                 {
-                    // Constant in formalPar list does not match actual value -> no match.
-                    continue;
+                    // Check whether parameter matches
+                    CommonTree formalPar = (CommonTree)f.GetChild(1);
+                    if (formalPar.Token.Type == INT
+                        && !new BigInteger(formalPar.Token.Text).Equals(paramValue))
+                    {
+                        // Constant in formalPar list does not match actual value -> no match.
+                        continue;
+                    }
+                    // Parameter (value for INT formal arg) as well as fct name agrees!
+                    return f;
                 }
-                // Parameter (value for INT formal arg) as well as fct name agrees!
-                return f;
             }
+            return null;
         }
-        return null;
-    }
 
-    /** Get value of name up call stack. */
-    public BigInteger getValue( string name )
-    {
-        BigInteger value;
-        if ( localMemory.TryGetValue( name, out value ) && value != null )
+        /** Get value of name up call stack. */
+        public BigInteger getValue(string name)
         {
-            return value;
+            BigInteger value;
+            if (localMemory.TryGetValue(name, out value) && value != null)
+            {
+                return value;
+            }
+            if (globalMemory.TryGetValue(name, out value) && value != null)
+            {
+                return value;
+            }
+            // not found in local memory or global memory
+            Console.Error.WriteLine("undefined variable " + name);
+            return new BigInteger("0");
         }
-        if ( globalMemory.TryGetValue( name, out value ) && value != null )
-        {
-            return value;
-        }
-        // not found in local memory or global memory
-        Console.Error.WriteLine( "undefined variable " + name );
-        return new BigInteger( "0" );
     }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Reduce.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Reduce.g3
index 0ed570b..db61e42 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Reduce.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Reduce.g3
@@ -2,20 +2,14 @@
 
 options
 {
-    tokenVocab=VecMath;      
-    ASTLabelType=CommonTree; 
-    output=AST;              
-    filter=true;             
-    language=CSharp3;
+	tokenVocab=VecMath;
+	ASTLabelType=CommonTree;
+	output=AST;
+	filter=true;
+	language=CSharp3;
 }
 
-
-@members 
-{ 
-   //public override IAstRuleReturnScope Topdown() { return topdown(); }
-   public override IAstRuleReturnScope Bottomup() { return bottomup(); } 
-} 
-
+@namespace{Antlr3.Runtime.Test.Composition}
 
 /** Rewrite: x+x to be 2*x, 2*x to be x<<1, x<<n<<m to be x<<(n+m) */
 bottomup
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Simplify.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Simplify.g3
index fd1fded..f1c2550 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Simplify.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Composition/Simplify.g3
@@ -9,12 +9,7 @@
     //rewrite=true;
 }
 
-@members 
-{ 
-   public override IAstRuleReturnScope Topdown() { return topdown(); }
-   public override IAstRuleReturnScope Bottomup() { return bottomup(); } 
-} 
-
+@namespace{Antlr3.Runtime.Test.Composition}
 
 topdown
     :   ^( MULT INT ^(VEC (e+=.)+) ) -> ^(VEC ^(MULT INT $e)+)
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/FastSimpleExpression.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/FastSimpleExpression.g3
index 1c51490..b0d5dfd 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/FastSimpleExpression.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/FastSimpleExpression.g3
@@ -41,6 +41,8 @@
 }
 
 @lexer::superClass{Antlr.Runtime.SlimLexer}
+@lexer::namespace{Antlr3.Runtime.Test}
+@parser::namespace{Antlr3.Runtime.Test}
 
 public
 expression
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/JavaCompat/Expr.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/JavaCompat/Expr.g3
index 65e7c5d..78c79cc 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/JavaCompat/Expr.g3
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/JavaCompat/Expr.g3
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -74,6 +74,9 @@
 HashMap memory = new HashMap();
 }
 
+@lexer::namespace{Antlr3.Runtime.Test.JavaCompat}
+@parser::namespace{Antlr3.Runtime.Test.JavaCompat}
+
 prog:   stat+ ;
 
 stat:   expr NEWLINE {JSystem.@out.println($expr.value);}
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3
new file mode 100644
index 0000000..29655ef
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3
@@ -0,0 +1,69 @@
+/*
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
+ * All rights reserved.
+ *
+ * Conversion to C#:
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+lexer grammar PreprocessorLexer;
+
+options
+{
+	language=CSharp3;
+}
+
+@namespace{Antlr3.Runtime.Test}
+
+PP_SKIPPED_CHARACTERS
+	:	{false}? => ~(F_NEW_LINE_CHARACTER | F_PP_POUND_SIGN) F_INPUT_CHARACTER*
+	;
+  
+DELIMITED_COMMENT
+	:	{true}? => '/*' .* '*/'
+	;
+  
+WHITESPACE
+	:	F_WHITESPACE {Skip();}
+	;
+  
+fragment F_WHITESPACE
+	:	(' ' | '\t' | '\v' | '\f')+ 
+	;
+
+fragment F_NEW_LINE_CHARACTER
+	:	'\r'
+	|	'\n'
+	;
+  
+fragment F_PP_POUND_SIGN
+	:	'#'
+	;
+  
+fragment F_INPUT_CHARACTER
+	:	~F_NEW_LINE_CHARACTER
+	;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3.cs
new file mode 100644
index 0000000..e095fbf
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorLexer.g3.cs
@@ -0,0 +1,38 @@
+/*
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
+ * All rights reserved.
+ *
+ * Conversion to C#:
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+namespace Antlr3.Runtime.Test
+{
+    partial class PreprocessorLexer
+    {
+    }
+}
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorTests.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorTests.cs
new file mode 100644
index 0000000..967f668
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/PreprocessorTests.cs
@@ -0,0 +1,58 @@
+/*
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
+ * All rights reserved.
+ *
+ * Conversion to C#:
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+namespace Antlr3.Runtime.Test
+{
+    using System.Collections.Generic;
+    using Antlr.Runtime;
+    using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+    [TestClass]
+    public class PreprocessorTests
+    {
+        [TestMethod]
+        public void TestEmptyComment()
+        {
+            string inputText = "/**/ ";
+            var input = new ANTLRStringStream(inputText);
+            var lexer = new PreprocessorLexer(input);
+            var tokenStream = new CommonTokenStream(lexer);
+            tokenStream.Fill();
+
+            List<IToken> tokens = tokenStream.GetTokens();
+            Assert.AreEqual(2, tokens.Count);
+            Assert.AreEqual(PreprocessorLexer.DELIMITED_COMMENT, tokens[0].Type);
+            Assert.AreEqual("/**/", tokens[0].Text);
+            Assert.AreEqual(PreprocessorLexer.EOF, tokens[1].Type);
+        }
+    }
+}
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs
index fd2190d..1e0fc38 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs
@@ -42,7 +42,7 @@
 [assembly: AssemblyConfiguration( "" )]
 [assembly: AssemblyCompany( "Pixel Mine, Inc." )]
 [assembly: AssemblyProduct( "Antlr3.Runtime.Test" )]
-[assembly: AssemblyCopyright("Copyright © Sam Harwell 2011")]
+[assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")]
 [assembly: AssemblyTrademark( "" )]
 [assembly: AssemblyCulture( "" )]
 [assembly: CLSCompliant( true )]
@@ -66,5 +66,5 @@
  *      the Major or Minor version is incremented.
  *   3. Revision is the Perforce changelist number associated with the release.
  */
-[assembly: AssemblyVersion("3.3.2.8098")]
-[assembly: AssemblyFileVersion("3.3.2.8098")]
+[assembly: AssemblyVersion("3.5.0.2")]
+[assembly: AssemblyFileVersion("3.5.0.2")]
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3 b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3
new file mode 100644
index 0000000..6bb7df4
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3
@@ -0,0 +1,47 @@
+/*
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
+ * All rights reserved.
+ *
+ * Conversion to C#:
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+tree grammar SynpredTreeParser;
+
+options
+{
+	language=CSharp3;
+	ASTLabelType=ITree;
+	output=AST;
+}
+
+@namespace{Antlr3.Runtime.Test}
+
+enterInsertOrDeleteData 
+	:	^( INSERT ( (DATA)=>DATA { _value = true; } | { _value = true; } ) .* )   
+	|	^( DELETE ( (DATA)=>DATA { _value = false; } | { _value = false; } ) .* )      
+	;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3.cs b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3.cs
new file mode 100644
index 0000000..f127aad
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime.Test/SynpredTreeParser.g3.cs
@@ -0,0 +1,41 @@
+/*
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
+ * All rights reserved.
+ *
+ * Conversion to C#:
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma warning disable 414 // The field 'fieldname' is assigned but its value is never used
+
+namespace Antlr3.Runtime.Test
+{
+    partial class SynpredTreeParser
+    {
+        private bool _value;
+    }
+}
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/ANTLRStringStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/ANTLRStringStream.cs
index 9904680..b3f11b4 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/ANTLRStringStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/ANTLRStringStream.cs
@@ -241,9 +241,9 @@
             {
                 state = markers[markDepth];
             }
-            state.p = p;
-            state.line = line;
-            state.charPositionInLine = charPositionInLine;
+            state.p = Index;
+            state.line = Line;
+            state.charPositionInLine = CharPositionInLine;
             lastMarker = markDepth;
             return markDepth;
         }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Antlr3.Runtime.csproj b/runtime/CSharp3/Sources/Antlr3.Runtime/Antlr3.Runtime.csproj
index 6de4bf7..5da739f 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Antlr3.Runtime.csproj
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Antlr3.Runtime.csproj
@@ -12,14 +12,8 @@
     <AssemblyName>Antlr3.Runtime</AssemblyName>
     <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
-    <SccProjectName>SAK</SccProjectName>
-    <SccLocalPath>SAK</SccLocalPath>
-    <SccAuxPath>SAK</SccAuxPath>
-    <SccProvider>SAK</SccProvider>
     <SignAssembly>true</SignAssembly>
-    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
-    <TargetFrameworkProfile>
-    </TargetFrameworkProfile>
+    <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
@@ -29,6 +23,7 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Debug\Antlr3.Runtime.xml</DocumentationFile>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -37,6 +32,7 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <DocumentationFile>bin\Release\Antlr3.Runtime.xml</DocumentationFile>
   </PropertyGroup>
   <ItemGroup>
     <Reference Include="System" />
@@ -105,6 +101,7 @@
     <Compile Include="Tree\CommonTreeAdaptor.cs" />
     <Compile Include="Tree\CommonTreeNodeStream.cs" />
     <Compile Include="Tree\DotTreeGenerator.cs" />
+    <Compile Include="Tree\IPositionTrackingStream.cs" />
     <Compile Include="Tree\ITree.cs" />
     <Compile Include="Tree\ITreeAdaptor.cs" />
     <Compile Include="Tree\ITreeNodeStream.cs" />
@@ -131,7 +128,7 @@
     <Compile Include="UnwantedTokenException.cs" />
   </ItemGroup>
   <ItemGroup>
-    <None Include="..\..\..\..\..\..\..\keys\antlr\Key.snk">
+    <None Include="..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk">
       <Link>Key.snk</Link>
     </None>
   </ItemGroup>
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/BaseRecognizer.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/BaseRecognizer.cs
index 5ba18f5..c62a5bf 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/BaseRecognizer.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/BaseRecognizer.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -37,15 +37,12 @@
     using ArgumentNullException = System.ArgumentNullException;
     using Array = System.Array;
     using Conditional = System.Diagnostics.ConditionalAttribute;
-    using Exception = System.Exception;
     using IDebugEventListener = Antlr.Runtime.Debug.IDebugEventListener;
     using MethodBase = System.Reflection.MethodBase;
-    using NotSupportedException = System.NotSupportedException;
     using Regex = System.Text.RegularExpressions.Regex;
     using StackFrame = System.Diagnostics.StackFrame;
     using StackTrace = System.Diagnostics.StackTrace;
     using TextWriter = System.IO.TextWriter;
-    using Type = System.Type;
 
     /** <summary>
      *  A generic recognizer that can handle recognizers generated from
@@ -97,6 +94,11 @@
             set;
         }
 
+        public virtual void SetState(RecognizerSharedState value)
+        {
+            this.state = value;
+        }
+
         protected virtual void InitDFAs()
         {
         }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/CommonTokenStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/CommonTokenStream.cs
index a1e4a29..28813cb 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/CommonTokenStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/CommonTokenStream.cs
@@ -166,6 +166,12 @@
             return i;
         }
 
+        public override void Reset()
+        {
+            base.Reset();
+            _p = SkipOffTokenChannels(0);
+        }
+
         protected override void Setup()
         {
             _p = 0;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/DFA.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/DFA.cs
index 37e2d06..76c4083 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/DFA.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/DFA.cs
@@ -32,6 +32,7 @@
 
 namespace Antlr.Runtime
 {
+    using ArgumentNullException = System.ArgumentNullException;
     using ConditionalAttribute = System.Diagnostics.ConditionalAttribute;
     using Console = System.Console;
     using IDebugEventListener = Antlr.Runtime.Debug.IDebugEventListener;
@@ -66,16 +67,16 @@
         /** <summary>Which recognizer encloses this DFA?  Needed to check backtracking</summary> */
         protected BaseRecognizer recognizer;
 
-        public readonly bool debug = false;
+        public bool debug = false;
 
         public DFA()
-            : this( new SpecialStateTransitionHandler( SpecialStateTransitionDefault ) )
+            : this(SpecialStateTransitionDefault)
         {
         }
 
         public DFA( SpecialStateTransitionHandler specialStateTransition )
         {
-            this.SpecialStateTransition = specialStateTransition ?? new SpecialStateTransitionHandler( SpecialStateTransitionDefault );
+            this.SpecialStateTransition = specialStateTransition ?? SpecialStateTransitionDefault;
         }
 
         public virtual string Description
@@ -95,47 +96,44 @@
          */
         public virtual int Predict( IIntStream input )
         {
-            if ( debug )
-            {
-                Console.Error.WriteLine( "Enter DFA.predict for decision " + decisionNumber );
-            }
+            if (input == null)
+                throw new ArgumentNullException("input");
+
+            DfaDebugMessage("Enter DFA.Predict for decision {0}", decisionNumber);
+
             int mark = input.Mark(); // remember where decision started in input
             int s = 0; // we always start at s0
             try
             {
-                for ( ; ; )
+                while (true)
                 {
-                    if ( debug )
-                        Console.Error.WriteLine( "DFA " + decisionNumber + " state " + s + " LA(1)=" + (char)input.LA( 1 ) + "(" + input.LA( 1 ) +
-                                           "), index=" + input.Index );
+                    DfaDebugMessage("DFA {0} state {1} LA(1)={2}({3}), index={4}", decisionNumber, s, (char)input.LA(1), input.LA(1), input.Index);
+
                     int specialState = special[s];
                     if ( specialState >= 0 )
                     {
-                        if ( debug )
-                        {
-                            Console.Error.WriteLine( "DFA " + decisionNumber +
-                                " state " + s + " is special state " + specialState );
-                        }
+                        DfaDebugMessage("DFA {0} state {1} is special state {2}", decisionNumber, s, specialState);
+
                         s = SpecialStateTransition( this, specialState, input );
-                        if ( debug )
-                        {
-                            Console.Error.WriteLine( "DFA " + decisionNumber +
-                                " returns from special state " + specialState + " to " + s );
-                        }
+
+                        DfaDebugMessage("DFA {0} returns from special state {1} to {2}", decisionNumber, specialState, s);
+
                         if ( s == -1 )
                         {
                             NoViableAlt( s, input );
                             return 0;
                         }
+
                         input.Consume();
                         continue;
                     }
+
                     if ( accept[s] >= 1 )
                     {
-                        if ( debug )
-                            Console.Error.WriteLine( "accept; predict " + accept[s] + " from state " + s );
+                        DfaDebugMessage("accept; predict {0} from state {1}", accept[s], s);
                         return accept[s];
                     }
+
                     // look for a normal char transition
                     char c = (char)input.LA( 1 ); // -1 == \uFFFF, all tokens fit in 65000 space
                     if ( c >= min[s] && c <= max[s] )
@@ -148,9 +146,9 @@
                             // eot[s]>=0 indicates that an EOT edge goes to another
                             // state.
                             if ( eot[s] >= 0 )
-                            {  // EOT Transition to accept state?
-                                if ( debug )
-                                    Console.Error.WriteLine( "EOT transition" );
+                            {
+                                // EOT Transition to accept state?
+                                DfaDebugMessage("EOT transition");
                                 s = eot[s];
                                 input.Consume();
                                 // TODO: I had this as return accept[eot[s]]
@@ -160,40 +158,35 @@
                                 // target?
                                 continue;
                             }
+
                             NoViableAlt( s, input );
                             return 0;
                         }
+
                         s = snext;
                         input.Consume();
                         continue;
                     }
+
                     if ( eot[s] >= 0 )
-                    {  // EOT Transition?
-                        if ( debug )
-                            Console.Error.WriteLine( "EOT transition" );
+                    {
+                        // EOT Transition?
+                        DfaDebugMessage("EOT transition");
                         s = eot[s];
                         input.Consume();
                         continue;
                     }
+
                     if ( c == unchecked( (char)TokenTypes.EndOfFile ) && eof[s] >= 0 )
-                    {  // EOF Transition to accept state?
-                        if ( debug )
-                            Console.Error.WriteLine( "accept via EOF; predict " + accept[eof[s]] + " from " + eof[s] );
+                    {
+                        // EOF Transition to accept state?
+                        DfaDebugMessage("accept via EOF; predict {0} from {1}", accept[eof[s]], eof[s]);
                         return accept[eof[s]];
                     }
+
                     // not in range and not EOF/EOT, must be invalid symbol
-                    if ( debug )
-                    {
-                        Console.Error.WriteLine( "min[" + s + "]=" + min[s] );
-                        Console.Error.WriteLine( "max[" + s + "]=" + max[s] );
-                        Console.Error.WriteLine( "eot[" + s + "]=" + eot[s] );
-                        Console.Error.WriteLine( "eof[" + s + "]=" + eof[s] );
-                        for ( int p = 0; p < transition[s].Length; p++ )
-                        {
-                            Console.Error.Write( transition[s][p] + " " );
-                        }
-                        Console.Error.WriteLine();
-                    }
+                    DfaDebugInvalidSymbol(s);
+
                     NoViableAlt( s, input );
                     return 0;
                 }
@@ -204,6 +197,26 @@
             }
         }
 
+        [Conditional("DEBUG_DFA")]
+        private void DfaDebugMessage(string format, params object[] args)
+        {
+            Console.Error.WriteLine(format, args);
+        }
+
+        [Conditional("DEBUG_DFA")]
+        private void DfaDebugInvalidSymbol(int s)
+        {
+            Console.Error.WriteLine("min[{0}]={1}", s, min[s]);
+            Console.Error.WriteLine("max[{0}]={1}", s, max[s]);
+            Console.Error.WriteLine("eot[{0}]={1}", s, eot[s]);
+            Console.Error.WriteLine("eof[{0}]={1}", s, eof[s]);
+
+            for (int p = 0; p < transition[s].Length; p++)
+                Console.Error.Write(transition[s][p] + " ");
+
+            Console.Error.WriteLine();
+        }
+
         protected virtual void NoViableAlt( int s, IIntStream input )
         {
             if ( recognizer.state.backtracking > 0 )
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Lexer.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Lexer.cs
index cf478c6..daf530d 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Lexer.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Lexer.cs
@@ -137,10 +137,7 @@
                 state.text = null;
                 if ( input.LA( 1 ) == CharStreamConstants.EndOfFile )
                 {
-                    IToken eof = new CommonToken((ICharStream)input, CharStreamConstants.EndOfFile, TokenChannels.Default, input.Index, input.Index);
-                    eof.Line = Line;
-                    eof.CharPositionInLine = CharPositionInLine;
-                    return eof;
+                    return GetEndOfFileToken();
                 }
                 try
                 {
@@ -173,6 +170,17 @@
             }
         }
 
+        /** Returns the EOF token (default), if you need
+         *  to return a custom token instead override this method.
+         */
+        public virtual IToken GetEndOfFileToken()
+        {
+            IToken eof = new CommonToken((ICharStream)input, CharStreamConstants.EndOfFile, TokenChannels.Default, input.Index, input.Index);
+            eof.Line = Line;
+            eof.CharPositionInLine = CharPositionInLine;
+            return eof;
+        }
+
         /** <summary>
          *  Instruct the lexer to skip creating a token for current lexer rule
          *  and look for another token.  nextToken() knows to keep looking when
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/FastQueue.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/FastQueue.cs
index 2dc5bfc..af975d7 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/FastQueue.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/FastQueue.cs
@@ -71,9 +71,9 @@
         }
 
         /** <summary>
-         *  Return element i elements ahead of current element.  i==0 gets
-         *  current element.  This is not an absolute index into the data list
-         *  since p defines the start of the real list.
+         * Return element {@code i} elements ahead of current element. {@code i==0}
+         * gets current element. This is not an absolute index into {@link #data}
+         * since {@code p} defines the start of the real list.
          *  </summary>
          */
         public virtual T this[int i]
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/LookaheadStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/LookaheadStream.cs
index 24dc0cb..14454a8 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/LookaheadStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Misc/LookaheadStream.cs
@@ -33,13 +33,16 @@
 namespace Antlr.Runtime.Misc
 {
     using ArgumentException = System.ArgumentException;
+    using Debug = System.Diagnostics.Debug;
     using InvalidOperationException = System.InvalidOperationException;
+    using NotSupportedException = System.NotSupportedException;
+    using ArgumentOutOfRangeException = System.ArgumentOutOfRangeException;
 
     /** <summary>
-     *  A lookahead queue that knows how to mark/release locations
-     *  in the buffer for backtracking purposes. Any markers force the FastQueue
-     *  superclass to keep all tokens until no more markers; then can reset
-     *  to avoid growing a huge buffer.
+     * A lookahead queue that knows how to mark/release locations in the buffer for
+     * backtracking purposes. Any markers force the {@link FastQueue} superclass to
+     * keep all elements until no more markers; then can reset to avoid growing a
+     * huge buffer.
      *  </summary>
      */
     public abstract class LookaheadStream<T>
@@ -47,10 +50,13 @@
         where T : class
     {
         /** Absolute token index. It's the index of the symbol about to be
-         *  read via LT(1). Goes from 0 to numtokens.
+         *  read via {@code LT(1)}. Goes from 0 to numtokens.
          */
         private int _currentElementIndex = 0;
 
+        /**
+         * This is the {@code LT(-1)} element for the first element in {@link #data}.
+         */
         private T _previousElement;
 
         /** Track object returned by nextElement upon end of stream;
@@ -84,9 +90,9 @@
             }
         }
 
-        public override void Clear()
+        public virtual void Reset()
         {
-            base.Clear();
+            Clear();
             _currentElementIndex = 0;
             _p = 0;
             _previousElement = null;
@@ -94,14 +100,17 @@
 
         /** <summary>
          *  Implement nextElement to supply a stream of elements to this
-         *  lookahead buffer.  Return eof upon end of the stream we're pulling from.
+         *  lookahead buffer.  Return EOF upon end of the stream we're pulling from.
          *  </summary>
          */
         public abstract T NextElement();
 
         public abstract bool IsEndOfFile(T o);
 
-        /** <summary>Get and remove first element in queue; override FastQueue.remove()</summary> */
+        /** <summary>
+         * Get and remove first element in queue; override
+         * {@link FastQueue#remove()}; it's the same, just checks for backtracking.
+         * </summary> */
         public override T Dequeue()
         {
             T o = this[0];
@@ -109,6 +118,7 @@
             // have we hit end of buffer and not backtracking?
             if ( _p == _data.Count && _markDepth == 0 )
             {
+                _previousElement = o;
                 // if so, it's an opportunity to start filling at index 0 again
                 Clear(); // size goes to 0, but retains memory
             }
@@ -119,7 +129,7 @@
         public virtual void Consume()
         {
             SyncAhead(1);
-            _previousElement = Dequeue();
+            Dequeue();
             _currentElementIndex++;
         }
 
@@ -201,34 +211,61 @@
 
         public virtual void Rewind( int marker )
         {
-            Seek( marker );
-            Release( marker );
+            _markDepth--;
+            int delta = _p - marker;
+            _currentElementIndex -= delta;
+            _p = marker;
         }
 
         public virtual void Rewind()
         {
-            Rewind( _lastMarker );
+            // rewind but do not release marker
+            int delta = _p - _lastMarker;
+            _currentElementIndex -= delta;
+            _p = _lastMarker;
         }
 
         /** <summary>
-         *  Seek to a 0-indexed position within data buffer.  Can't handle
-         *  case where you seek beyond end of existing buffer.  Normally used
-         *  to seek backwards in the buffer. Does not force loading of nodes.
-         *  Doesn't see to absolute position in input stream since this stream
-         *  is unbuffered. Seeks only into our moving window of elements.
+         * Seek to a 0-indexed absolute token index. Normally used to seek backwards
+         * in the buffer. Does not force loading of nodes.
          *  </summary>
+         *  <remarks>
+         * To preserve backward compatibility, this method allows seeking past the
+         * end of the currently buffered data. In this case, the input pointer will
+         * be moved but the data will only actually be loaded upon the next call to
+         * {@link #consume} or {@link #LT} for {@code k>0}.
+         *  </remarks>
          */
         public virtual void Seek( int index )
         {
-            _p = index;
+            if (index < 0)
+                throw new ArgumentOutOfRangeException("index");
+
+            int delta = _currentElementIndex - index;
+            if (_p - delta < 0)
+                throw new NotSupportedException("can't seek before the beginning of this stream's buffer");
+
+            _p -= delta;
+            _currentElementIndex = index;
         }
 
         protected virtual T LB(int k)
         {
-            if (k == 1)
+            Debug.Assert(k > 0);
+
+            int index = _p - k;
+            if (index == -1)
                 return _previousElement;
 
-            throw new ArgumentException("can't look backwards more than one token in this stream");
+            // if k>0 then we know index < data.size(). avoid the double-check for
+            // performance.
+            if (index >= 0 /*&& index < data.size()*/)
+                return _data[index];
+
+            if (index < -1)
+                throw new NotSupportedException("can't look more than one token before the beginning of this stream's buffer");
+
+            throw new NotSupportedException("can't look past the end of this stream's buffer using LB(int)");
         }
     }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/NoViableAltException.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/NoViableAltException.cs
index 6478c6f..4f37001 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/NoViableAltException.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/NoViableAltException.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -66,7 +66,12 @@
         }
 
         public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
-            : base(input)
+            : this(grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
+        {
+        }
+
+        public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
+            : base(input, k)
         {
             this._grammarDecisionDescription = grammarDecisionDescription;
             this._decisionNumber = decisionNumber;
@@ -74,7 +79,12 @@
         }
 
         public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
-            : base(message, input)
+            : this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
+        {
+        }
+
+        public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
+            : base(message, input, k)
         {
             this._grammarDecisionDescription = grammarDecisionDescription;
             this._decisionNumber = decisionNumber;
@@ -82,7 +92,12 @@
         }
 
         public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, Exception innerException)
-            : base(message, input, innerException)
+            : this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1, innerException)
+        {
+        }
+
+        public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k, Exception innerException)
+            : base(message, input, k, innerException)
         {
             this._grammarDecisionDescription = grammarDecisionDescription;
             this._decisionNumber = decisionNumber;
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Properties/AssemblyInfo.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Properties/AssemblyInfo.cs
index 1489fde..cc3425f 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Properties/AssemblyInfo.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Properties/AssemblyInfo.cs
@@ -41,9 +41,9 @@
 [assembly: AssemblyTitle( "Antlr3.Runtime" )]
 [assembly: AssemblyDescription( "" )]
 [assembly: AssemblyConfiguration( "" )]
-[assembly: AssemblyCompany( "Pixel Mine, Inc." )]
+[assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )]
 [assembly: AssemblyProduct( "Antlr3.Runtime" )]
-[assembly: AssemblyCopyright("Copyright © Sam Harwell 2011")]
+[assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")]
 [assembly: AssemblyTrademark( "" )]
 [assembly: AssemblyCulture( "" )]
 [assembly: CLSCompliant( true )]
@@ -68,5 +68,5 @@
  *      the Major or Minor version is incremented.
  *   3. Revision is the Perforce changelist number associated with the release.
  */
-[assembly: AssemblyVersion("3.3.4.8517")]
-[assembly: AssemblyFileVersion("3.3.4.8517")]
+[assembly: AssemblyVersion("3.5.0.2")]
+[assembly: AssemblyFileVersion("3.5.0.2")]
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/RecognitionException.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/RecognitionException.cs
index f0c5662..007560d 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/RecognitionException.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/RecognitionException.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -34,9 +34,9 @@
 {
     using Antlr.Runtime.Tree;
 
-    using ArgumentException = System.ArgumentException;
     using ArgumentNullException = System.ArgumentNullException;
     using Exception = System.Exception;
+    using NotSupportedException = System.NotSupportedException;
     using SerializationInfo = System.Runtime.Serialization.SerializationInfo;
     using StreamingContext = System.Runtime.Serialization.StreamingContext;
 
@@ -78,6 +78,11 @@
         /** <summary>What input stream did the error occur in?</summary> */
         private IIntStream _input;
 
+        /// <summary>
+        /// What was the lookahead index when this exception was thrown?
+        /// </summary>
+        private int _k;
+
         /** <summary>What is index of token/char were we looking at when the error occurred?</summary> */
         private int _index;
 
@@ -127,8 +132,13 @@
         {
         }
 
-        public RecognitionException( IIntStream input )
-            : this("A recognition error occurred.", input, null)
+        public RecognitionException(IIntStream input)
+            : this("A recognition error occurred.", input, 1, null)
+        {
+        }
+
+        public RecognitionException(IIntStream input, int k)
+            : this("A recognition error occurred.", input, k, null)
         {
         }
 
@@ -138,7 +148,12 @@
         }
 
         public RecognitionException(string message, IIntStream input)
-            : this(message, input, null)
+            : this(message, input, 1, null)
+        {
+        }
+
+        public RecognitionException(string message, IIntStream input, int k)
+            : this(message, input, k, null)
         {
         }
 
@@ -148,15 +163,21 @@
         }
 
         public RecognitionException(string message, IIntStream input, Exception innerException)
+            : this(message, input, 1, innerException)
+        {
+        }
+
+        public RecognitionException(string message, IIntStream input, int k, Exception innerException)
             : base(message, innerException)
         {
             this._input = input;
+            this._k = k;
             if (input != null)
             {
-                this._index = input.Index;
+                this._index = input.Index + k - 1;
                 if (input is ITokenStream)
                 {
-                    this._token = ((ITokenStream)input).LT(1);
+                    this._token = ((ITokenStream)input).LT(k);
                     this._line = _token.Line;
                     this._charPositionInLine = _token.CharPositionInLine;
                 }
@@ -164,20 +185,31 @@
                 ITreeNodeStream tns = input as ITreeNodeStream;
                 if (tns != null)
                 {
-                    ExtractInformationFromTreeNodeStream(tns);
+                    ExtractInformationFromTreeNodeStream(tns, k);
                 }
                 else
                 {
                     ICharStream charStream = input as ICharStream;
                     if (charStream != null)
                     {
-                        this._c = input.LA(1);
-                        this._line = ((ICharStream)input).Line;
-                        this._charPositionInLine = ((ICharStream)input).CharPositionInLine;
+                        int mark = input.Mark();
+                        try
+                        {
+                            for (int i = 0; i < k - 1; i++)
+                                input.Consume();
+
+                            this._c = input.LA(1);
+                            this._line = ((ICharStream)input).Line;
+                            this._charPositionInLine = ((ICharStream)input).CharPositionInLine;
+                        }
+                        finally
+                        {
+                            input.Rewind(mark);
+                        }
                     }
                     else
                     {
-                        this._c = input.LA(1);
+                        this._c = input.LA(k);
                     }
                 }
             }
@@ -241,6 +273,14 @@
             }
         }
 
+        public int Lookahead
+        {
+            get
+            {
+                return _k;
+            }
+        }
+
         public IToken Token
         {
             get
@@ -329,6 +369,19 @@
         protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input)
         {
             this._node = input.LT(1);
+
+            object positionNode = null;
+            IPositionTrackingStream positionTrackingStream = input as IPositionTrackingStream;
+            if (positionTrackingStream != null)
+            {
+                positionNode = positionTrackingStream.GetKnownPositionElement(false);
+                if (positionNode == null)
+                {
+                    positionNode = positionTrackingStream.GetKnownPositionElement(true);
+                    this._approximateLineInfo = positionNode != null;
+                }
+            }
+
             ITokenStreamInformation streamInformation = input as ITokenStreamInformation;
             if (streamInformation != null)
             {
@@ -345,7 +398,7 @@
             else
             {
                 ITreeAdaptor adaptor = input.TreeAdaptor;
-                IToken payload = adaptor.GetToken(_node);
+                IToken payload = adaptor.GetToken(positionNode ?? _node);
                 if (payload != null)
                 {
                     this._token = payload;
@@ -365,12 +418,13 @@
                                 this._approximateLineInfo = true;
                                 break;
                             }
+
                             --i;
                             try
                             {
                                 priorNode = input.LT(i);
                             }
-                            catch (ArgumentException)
+                            catch (NotSupportedException)
                             {
                                 priorNode = null;
                             }
@@ -400,5 +454,21 @@
                 }
             }
         }
+
+        protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input, int k)
+        {
+            int mark = input.Mark();
+            try
+            {
+                for (int i = 0; i < k - 1; i++)
+                    input.Consume();
+
+                ExtractInformationFromTreeNodeStream(input);
+            }
+            finally
+            {
+                input.Rewind(mark);
+            }
+        }
     }
 }
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/BaseTree.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/BaseTree.cs
index 79f3d97..9327860 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/BaseTree.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/BaseTree.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
+ * [The "BSD license"]
  * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -286,6 +286,30 @@
             t.ChildIndex = i;
         }
 
+        /** Insert child t at child position i (0..n-1) by shifting children
+         *  i+1..n-1 to the right one position. Set parent / indexes properly
+         *  but does NOT collapse nil-rooted t's that come in here like addChild.
+         */
+        public virtual void InsertChild(int i, ITree t)
+        {
+            if (i < 0)
+                throw new ArgumentOutOfRangeException("i");
+            if (i > ChildCount)
+                throw new ArgumentException();
+
+            if (i == ChildCount)
+            {
+                AddChild(t);
+                return;
+            }
+
+            Children.Insert(i, t);
+
+            // walk others to increment their child indexes
+            // set index, parent of this one too
+            this.FreshenParentAndChildIndexes(i);
+        }
+
         public virtual object DeleteChild( int i )
         {
             if (i < 0)
@@ -428,6 +452,25 @@
             }
         }
 
+        public virtual void FreshenParentAndChildIndexesDeeply()
+        {
+            FreshenParentAndChildIndexesDeeply(0);
+        }
+
+        public virtual void FreshenParentAndChildIndexesDeeply(int offset)
+        {
+            int n = ChildCount;
+            for (int c = offset; c < n; c++)
+            {
+                ITree child = GetChild(c);
+                child.ChildIndex = c;
+                child.Parent = this;
+                BaseTree baseTree = child as BaseTree;
+                if (baseTree != null)
+                    baseTree.FreshenParentAndChildIndexesDeeply();
+            }
+        }
+
         public virtual void SanityCheckParentAndChildIndexes()
         {
             SanityCheckParentAndChildIndexes( null, -1 );
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs
index 45c46be..f9cb0a7 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs
@@ -1,10 +1,10 @@
 /*
- * [The "BSD licence"]
- * Copyright (c) 2005-2008 Terence Parr
+ * [The "BSD license"]
+ * Copyright (c) 2011 Terence Parr
  * All rights reserved.
  *
  * Conversion to C#:
- * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
+ * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -36,35 +36,45 @@
     using Antlr.Runtime.Misc;
 
     using StringBuilder = System.Text.StringBuilder;
-    using NotSupportedException = System.NotSupportedException;
 
     [System.Serializable]
-    public class CommonTreeNodeStream : LookaheadStream<object>, ITreeNodeStream
+    public class CommonTreeNodeStream : LookaheadStream<object>, ITreeNodeStream, IPositionTrackingStream
     {
         public const int DEFAULT_INITIAL_BUFFER_SIZE = 100;
         public const int INITIAL_CALL_STACK_SIZE = 10;
 
         /** <summary>Pull nodes from which tree?</summary> */
-        object _root;
+        private readonly object _root;
 
         /** <summary>If this tree (root) was created from a token stream, track it.</summary> */
         protected ITokenStream tokens;
 
         /** <summary>What tree adaptor was used to build these trees</summary> */
         [System.NonSerialized]
-        ITreeAdaptor _adaptor;
+        private ITreeAdaptor _adaptor;
 
         /** The tree iterator we are using */
-        TreeIterator _it;
+        private readonly TreeIterator _it;
 
         /** <summary>Stack of indexes used for push/pop calls</summary> */
-        Stack<int> _calls;
+        private Stack<int> _calls;
 
         /** <summary>Tree (nil A B C) trees like flat A B C streams</summary> */
-        bool _hasNilRoot = false;
+        private bool _hasNilRoot = false;
 
         /** <summary>Tracks tree depth.  Level=0 means we're at root node level.</summary> */
-        int _level = 0;
+        private int _level = 0;
+
+        /**
+         * Tracks the last node before the start of {@link #data} which contains
+         * position information to provide information for error reporting. This is
+         * tracked in addition to {@link #prevElement} which may or may not contain
+         * position information.
+         *
+         * @see #hasPositionInformation
+         * @see RecognitionException#extractInformationFromTreeNodeStream
+         */
+        private object _previousLocationElement;
 
         public CommonTreeNodeStream( object tree )
             : this( new CommonTreeAdaptor(), tree )
@@ -97,6 +107,7 @@
             {
                 return tokens;
             }
+
             set
             {
                 tokens = value;
@@ -138,12 +149,13 @@
 
         #endregion
 
-        public virtual void Reset()
+        public override void Reset()
         {
-            base.Clear();
+            base.Reset();
             _it.Reset();
             _hasNilRoot = false;
             _level = 0;
+            _previousLocationElement = null;
             if ( _calls != null )
                 _calls.Clear();
         }
@@ -181,6 +193,15 @@
             return t;
         }
 
+        public override object Dequeue()
+        {
+            object result = base.Dequeue();
+            if (_p == 0 && HasPositionInformation(PreviousElement))
+                _previousLocationElement = PreviousElement;
+
+            return result;
+        }
+
         public override bool IsEndOfFile(object o)
         {
             return TreeAdaptor.GetType(o) == CharStreamConstants.EndOfFile;
@@ -197,9 +218,8 @@
         public virtual void Push( int index )
         {
             if ( _calls == null )
-            {
                 _calls = new Stack<int>();
-            }
+
             _calls.Push( _p ); // save current index
             Seek( index );
         }
@@ -214,6 +234,44 @@
             return ret;
         }
 
+        /**
+         * Returns an element containing position information. If {@code allowApproximateLocation} is {@code false}, then
+         * this method will return the {@code LT(1)} element if it contains position information, and otherwise return {@code null}.
+         * If {@code allowApproximateLocation} is {@code true}, then this method will return the last known element containing position information.
+         *
+         * @see #hasPositionInformation
+         */
+        public object GetKnownPositionElement(bool allowApproximateLocation)
+        {
+            object node = _data[_p];
+            if (HasPositionInformation(node))
+                return node;
+
+            if (!allowApproximateLocation)
+                return null;
+
+            for (int index = _p - 1; index >= 0; index--)
+            {
+                node = _data[index];
+                if (HasPositionInformation(node))
+                    return node;
+            }
+
+            return _previousLocationElement;
+        }
+
+        public bool HasPositionInformation(object node)
+        {
+            IToken token = TreeAdaptor.GetToken(node);
+            if (token == null)
+                return false;
+
+            if (token.Line <= 0)
+                return false;
+
+            return true;
+        }
+
         #region Tree rewrite interface
 
         public virtual void ReplaceChildren( object parent, int startChildIndex, int stopChildIndex, object t )
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/IPositionTrackingStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/IPositionTrackingStream.cs
new file mode 100644
index 0000000..8bc8945
--- /dev/null
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/IPositionTrackingStream.cs
@@ -0,0 +1,59 @@
+/*
+ [The "BSD license"]
+ Copyright (c) 2012 Terence Parr
+ Copyright (c) 2012 Sam Harwell
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+ 1. Redistributions of source code must retain the above copyright
+     notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+     notice, this list of conditions and the following disclaimer in the
+     documentation and/or other materials provided with the distribution.
+ 3. The name of the author may not be used to endorse or promote products
+     derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+namespace Antlr.Runtime.Tree
+{
+    /**
+     *
+     * @author Sam Harwell
+     */
+    public interface IPositionTrackingStream
+    {
+        /**
+         * Returns an element containing concrete information about the current
+         * position in the stream.
+         *
+         * @param allowApproximateLocation if {@code false}, this method returns
+         * {@code null} if an element containing exact information about the current
+         * position is not available
+         */
+        object GetKnownPositionElement(bool allowApproximateLocation);
+
+        /**
+         * Determines if the specified {@code element} contains concrete position
+         * information.
+         *
+         * @param element the element to check
+         * @return {@code true} if {@code element} contains concrete position
+         * information, otherwise {@code false}
+         */
+        bool HasPositionInformation(object element);
+
+    }
+}
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/ITreeNodeStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/ITreeNodeStream.cs
index b133f39..8f3f30a 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/ITreeNodeStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/ITreeNodeStream.cs
@@ -47,18 +47,18 @@
         }
 
         /** <summary>
-         *  Get tree node at current input pointer + i ahead where i=1 is next node.
-         *  i&lt;0 indicates nodes in the past.  So LT(-1) is previous node, but
-         *  implementations are not required to provide results for k &lt; -1.
-         *  LT(0) is undefined.  For i&gt;=n, return null.
-         *  Return null for LT(0) and any index that results in an absolute address
-         *  that is negative.
+         * Get tree node at current input pointer + {@code k} ahead where
+         * {@code k==1} is next node. {@code k<0} indicates nodes in the past. So
+         * {@code LT(-1)} is previous node, but implementations are not required to
+         * provide results for {@code k < -1}. {@code LT(0)} is undefined. For
+         * {@code k<=n}, return {@code null}. Return {@code null} for {@code LT(0)}
+         * and any index that results in an absolute address that is negative.
          *  </summary>
          *
          *  <remarks>
-         *  This is analogus to the LT() method of the TokenStream, but this
-         *  returns a tree node instead of a token.  Makes code gen identical
-         *  for both parser and tree grammars. :)
+         * This is analogous to {@link TokenStream#LT}, but this returns a tree node
+         * instead of a {@link Token}. Makes code generation identical for both
+         * parser and tree grammars.
          *  </remarks>
          */
         object LT( int k );
@@ -74,10 +74,11 @@
         }
 
         /** <summary>
-         *  If the tree associated with this stream was created from a TokenStream,
-         *  you can specify it here.  Used to do rule $text attribute in tree
-         *  parser.  Optional unless you use tree parser rule text attribute
-         *  or output=template and rewrite=true options.
+         * If the tree associated with this stream was created from a
+         * {@link TokenStream}, you can specify it here. Used to do rule
+         * {@code $text} attribute in tree parser. Optional unless you use tree
+         * parser rule {@code $text} attribute or {@code output=template} and
+         * {@code rewrite=true} options.
          *  </summary>
          */
         ITokenStream TokenStream
@@ -96,11 +97,11 @@
         }
 
         /** <summary>
-         *  As we flatten the tree, we use UP, DOWN nodes to represent
-         *  the tree structure.  When debugging we need unique nodes
-         *  so we have to instantiate new ones.  When doing normal tree
-         *  parsing, it's slow and a waste of memory to create unique
-         *  navigation nodes.  Default should be false;
+         * As we flatten the tree, we use {@link Token#UP}, {@link Token#DOWN} nodes
+         * to represent the tree structure. When debugging we need unique nodes so
+         * we have to instantiate new ones. When doing normal tree parsing, it's
+         * slow and a waste of memory to create unique navigation nodes. Default
+         * should be {@code false}.
          *  </summary>
          */
         bool UniqueNavigationNodes
@@ -110,11 +111,11 @@
         }
 
         /** <summary>
-         *  Return the text of all nodes from start to stop, inclusive.
-         *  If the stream does not buffer all the nodes then it can still
-         *  walk recursively from start until stop.  You can always return
-         *  null or "" too, but users should not access $ruleLabel.text in
-         *  an action of course in that case.
+         * Return the text of all nodes from {@code start} to {@code stop},
+         * inclusive. If the stream does not buffer all the nodes then it can still
+         * walk recursively from start until stop. You can always return
+         * {@code null} or {@code ""} too, but users should not access
+         * {@code $ruleLabel.text} in an action of course in that case.
          *  </summary>
          */
         string ToString( object start, object stop );
@@ -123,17 +124,18 @@
         #region REWRITING TREES (used by tree parser)
 
         /** <summary>
-         *  Replace from start to stop child index of parent with t, which might
-         *  be a list.  Number of children may be different
-         *  after this call.  The stream is notified because it is walking the
-         *  tree and might need to know you are monkeying with the underlying
-         *  tree.  Also, it might be able to modify the node stream to avoid
-         *  restreaming for future phases.
+         * Replace children of {@code parent} from index {@code startChildIndex} to
+         * {@code stopChildIndex} with {@code t}, which might be a list. Number of
+         * children may be different after this call. The stream is notified because
+         * it is walking the tree and might need to know you are monkeying with the
+         * underlying tree. Also, it might be able to modify the node stream to
+         * avoid restreaming for future phases.
          *  </summary>
          *
          *  <remarks>
-         *  If parent is null, don't do anything; must be at root of overall tree.
-         *  Can't replace whatever points to the parent externally.  Do nothing.
+         * If {@code parent} is {@code null}, don't do anything; must be at root of
+         * overall tree. Can't replace whatever points to the parent externally. Do
+         * nothing.
          *  </remarks>
          */
         void ReplaceChildren( object parent, int startChildIndex, int stopChildIndex, object t );
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/RewriteRuleElementStream.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/RewriteRuleElementStream.cs
index 8e3d5b0..cb76ace 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/RewriteRuleElementStream.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/RewriteRuleElementStream.cs
@@ -71,10 +71,7 @@
         /** <summary>Once a node / subtree has been used in a stream, it must be dup'd
          *  from then on.  Streams are reset after subrules so that the streams
          *  can be reused in future subrules.  So, reset must set a dirty bit.
-         *  If dirty, then next() always returns a dup.
-         *
-         *  I wanted to use "naughty bit" here, but couldn't think of a way
-         *  to use "naughty".
+         *  If dirty, then next() always returns a dup.</summary>
          */
         protected bool dirty = false;
 
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeFilter.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeFilter.cs
index ef7b412..ba44e2d 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeFilter.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeFilter.cs
@@ -58,8 +58,8 @@
             try
             {
                 // share TreeParser object but not parsing-related state
-                state = new RecognizerSharedState();
-                input = new CommonTreeNodeStream( originalAdaptor, t );
+                SetState(new RecognizerSharedState());
+                SetTreeNodeStream(new CommonTreeNodeStream(originalAdaptor, t));
                 ( (CommonTreeNodeStream)input ).TokenStream = originalTokenStream;
                 BacktrackingLevel = 1;
                 whichRule();
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeParser.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeParser.cs
index 927ee23..f5a1508 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeParser.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeParser.cs
@@ -58,13 +58,13 @@
         public TreeParser( ITreeNodeStream input )
             : base() // highlight that we go to super to set state object
         {
-            SetTreeNodeStream( input );
+            this.input = input;
         }
 
         public TreeParser( ITreeNodeStream input, RecognizerSharedState state )
             : base( state ) // share the state object with another parser
         {
-            SetTreeNodeStream( input );
+            this.input = input;
         }
 
         public override void Reset()
diff --git a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeRewriter.cs b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeRewriter.cs
index b610c2c..16a38a2 100644
--- a/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeRewriter.cs
+++ b/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/TreeRewriter.cs
@@ -67,8 +67,8 @@
             try
             {
                 // share TreeParser object but not parsing-related state
-                state = new RecognizerSharedState();
-                input = new CommonTreeNodeStream( originalAdaptor, t );
+                SetState(new RecognizerSharedState());
+                SetTreeNodeStream(new CommonTreeNodeStream(originalAdaptor, t));
                 ( (CommonTreeNodeStream)input ).TokenStream = originalTokenStream;
                 BacktrackingLevel = 1;
                 IAstRuleReturnScope r = whichRule();
@@ -119,12 +119,12 @@
         // methods the downup strategy uses to do the up and down rules.
         // to override, just define tree grammar rule topdown and turn on
         // filter=true.
-        public virtual IAstRuleReturnScope Topdown()
+        protected virtual IAstRuleReturnScope Topdown()
         {
             return null;
         }
 
-        public virtual IAstRuleReturnScope Bottomup()
+        protected virtual IAstRuleReturnScope Bottomup()
         {
             return null;
         }
diff --git a/runtime/Cpp/include/antlr3.hpp b/runtime/Cpp/include/antlr3.hpp
new file mode 100755
index 0000000..4e40ba4
--- /dev/null
+++ b/runtime/Cpp/include/antlr3.hpp
@@ -0,0 +1,60 @@
+#ifndef	_ANTLR3_HPP
+#define	_ANTLR3_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <string>
+#include <sstream>
+
+#include    "antlr3defs.hpp"
+
+#include    "antlr3errors.hpp"
+#include    "antlr3memory.hpp"
+
+#include	"antlr3recognizersharedstate.hpp"
+#include    "antlr3baserecognizer.hpp"
+#include    "antlr3bitset.hpp"
+#include    "antlr3collections.hpp"
+#include    "antlr3commontoken.hpp"
+#include	"antlr3commontree.hpp"
+#include    "antlr3commontreeadaptor.hpp"
+#include    "antlr3cyclicdfa.hpp"
+#include	"antlr3debugeventlistener.hpp"
+#include    "antlr3exception.hpp"
+#include    "antlr3filestream.hpp"
+#include    "antlr3intstream.hpp"
+#include    "antlr3input.hpp"
+#include    "antlr3tokenstream.hpp"
+#include	"antlr3commontreenodestream.hpp"
+#include    "antlr3lexer.hpp"
+#include    "antlr3parser.hpp"
+#include    "antlr3rewritestreams.hpp"
+#include	"antlr3traits.hpp"
+#include    "antlr3treeparser.hpp"
+
+#endif
diff --git a/runtime/Cpp/include/antlr3.inl b/runtime/Cpp/include/antlr3.inl
new file mode 100755
index 0000000..79974af
--- /dev/null
+++ b/runtime/Cpp/include/antlr3.inl
@@ -0,0 +1,9 @@
+ANTLR_BEGIN_NAMESPACE()
+
+//static 
+ANTLR_INLINE void GenericStream::displayRecognitionError( const StringType& str )
+{
+	fprintf(stderr, str.c_str() );
+}
+
+ANTLR_END_NAMESPACE()
\ No newline at end of file
diff --git a/runtime/Cpp/include/antlr3baserecognizer.hpp b/runtime/Cpp/include/antlr3baserecognizer.hpp
new file mode 100755
index 0000000..f125400
--- /dev/null
+++ b/runtime/Cpp/include/antlr3baserecognizer.hpp
@@ -0,0 +1,512 @@
+/** \file
+ * Defines the basic structure to support recognizing by either a lexer,
+ * parser, or tree parser.
+ * \addtogroup BaseRecognizer
+ * @{
+ */
+#ifndef	_ANTLR3_BASERECOGNIZER_HPP
+#define	_ANTLR3_BASERECOGNIZER_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    "antlr3defs.hpp"
+#include    "antlr3collections.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+/** \brief Base tracking context structure for all types of
+ * recognizers.
+ */
+template< class ImplTraits, class StreamType >
+class BaseRecognizer : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::AllocPolicyType	AllocPolicyType;
+	typedef typename StreamType::IntStreamType	IntStreamType;
+	typedef typename ComponentTypeFinder<ImplTraits, StreamType>::ComponentType  SuperType;
+	typedef typename StreamType::UnitType		UnitType;
+	typedef typename ImplTraits::template ExceptionBaseType<StreamType> ExceptionBaseType;
+	typedef typename ImplTraits::BitsetType BitsetType;
+	typedef typename ImplTraits::BitsetListType		BitsetListType;
+	typedef typename ImplTraits::StringType	StringType;
+	typedef typename ImplTraits::template RecognizerSharedStateType<StreamType>  RecognizerSharedStateType;
+	typedef typename ImplTraits::DebugEventListenerType DebugEventListenerType;
+	typedef typename ImplTraits::LexerType LexerType;
+	typedef typename ImplTraits::ParserType ParserType;
+	typedef typename ImplTraits::TreeParserType TreeParserType;
+
+	typedef typename AllocPolicyType::template StackType<StringType>  StringStackType;
+	typedef typename AllocPolicyType::template ListType<StringType>  StringListType;
+
+private:
+	/// A pointer to the shared recognizer state, such that multiple
+	/// recognizers can use the same inputs streams and so on (in
+	/// the case of grammar inheritance for instance.
+	///
+	RecognizerSharedStateType*		m_state;
+
+	/// If set to something other than NULL, then this structure is
+	/// points to an instance of the debugger interface. In general, the
+	/// debugger is only referenced internally in recovery/error operations
+	/// so that it does not cause overhead by having to check this pointer
+	/// in every function/method
+	///
+	DebugEventListenerType*		m_debugger;
+
+
+public:
+	BaseRecognizer(ANTLR_UINT32 sizeHint, RecognizerSharedStateType* state);
+
+	SuperType* get_super();
+	RecognizerSharedStateType* get_state() const;
+	DebugEventListenerType* get_debugger() const;
+	void  set_state( RecognizerSharedStateType* state );
+	void  set_debugger( DebugEventListenerType* debugger );
+
+    /// Match current input symbol against ttype.  Upon error, do one token
+	/// insertion or deletion if possible.
+	/// To turn off single token insertion or deletion error
+	/// recovery, override mismatchRecover() and have it call
+	/// plain mismatch(), which does not recover.  Then any error
+	/// in a rule will cause an exception and immediate exit from
+	/// rule.  Rule would recover by resynchronizing to the set of
+	/// symbols that can follow rule ref.
+	///
+    const UnitType*	match(ANTLR_UINT32 ttype, BitsetListType* follow);
+
+	/// Consumes the next token, whatever it is, and resets the recognizer state
+	/// so that it is not in error.
+	///
+	/// \param recognizer
+	/// Recognizer context pointer
+	///
+    void	matchAny();
+
+	/// function that decides if the token ahead of the current one is the
+	/// one we were loking for, in which case the curernt one is very likely extraneous
+	/// and can be reported that way.
+	///
+	bool mismatchIsUnwantedToken(IntStreamType* input, ANTLR_UINT32 ttype);
+
+	/// function that decides if the current token is one that can logically
+	/// follow the one we were looking for, in which case the one we were looking for is
+	/// probably missing from the input.
+	///
+	bool mismatchIsMissingToken(IntStreamType* input, BitsetListType* follow);
+
+    /// Factor out what to do upon token mismatch so tree parsers can behave
+	/// differently.  Override and call mismatchRecover(input, ttype, follow)
+	/// to get single token insertion and deletion.  Use this to turn off
+	/// single token insertion and deletion. Override mismatchRecover
+	/// to call this instead.
+	///
+	/// \remark mismatch only works for parsers and must be overridden for anything else.
+	///
+    void mismatch(ANTLR_UINT32 ttype, BitsetListType* follow);
+
+    /// Report a recognition problem.
+	///
+	/// This method sets errorRecovery to indicate the parser is recovering
+	/// not parsing.  Once in recovery mode, no errors are generated.
+	/// To get out of recovery mode, the parser must successfully match
+	/// a token (after a resync).  So it will go:
+	///
+	///		1. error occurs
+	///		2. enter recovery mode, report error
+	///		3. consume until token found in resynch set
+	///		4. try to resume parsing
+	///		5. next match() will reset errorRecovery mode
+	///
+	/// If you override, make sure to update errorCount if you care about that.
+	///
+    void	reportError();
+	void	reportError( ClassForwarder<LexerType> );
+	template<typename CompType>
+	void	reportError( ClassForwarder<CompType> );
+
+    /** Function that is called to display a recognition error message. You may
+     *  override this function independently of (*reportError)() above as that function calls
+     *  this one to do the actual exception printing.
+     */
+    void	displayRecognitionError(ANTLR_UINT8** tokenNames);
+
+	/// Get number of recognition errors (lexer, parser, tree parser).  Each
+	/// recognizer tracks its own number.  So parser and lexer each have
+	/// separate count.  Does not count the spurious errors found between
+	/// an error and next valid token match
+	///
+	/// \see reportError()
+	///
+	ANTLR_UINT32 getNumberOfSyntaxErrors();
+
+    /** Function that recovers from an error found in the input stream.
+     *  Generally, this will be a #ANTLR3_EXCEPTION_NOVIABLE_ALT but it could also
+     *  be from a mismatched token that the (*match)() could not recover from.
+     */
+    void	recover();
+
+    /** function that is a hook to listen to token consumption during error recovery.
+     *  This is mainly used by the debug parser to send events to the listener.
+     */
+    void	beginResync();
+
+    /** function that is a hook to listen to token consumption during error recovery.
+     *  This is mainly used by the debug parser to send events to the listener.
+     */
+    void	endResync();
+
+	/** function that is a hook to listen to token consumption during error recovery.
+     *  This is mainly used by the debug parser to send events to the listener.
+     */
+    void	beginBacktrack(ANTLR_UINT32 level);
+
+    /** function that is a hook to listen to token consumption during error recovery.
+     *  This is mainly used by the debug parser to send events to the listener.
+     */
+    void	endBacktrack(ANTLR_UINT32 level, bool successful);
+
+    /// Compute the error recovery set for the current rule.
+	/// Documentation below is from the Java implementation.
+	///
+	/// During rule invocation, the parser pushes the set of tokens that can
+	/// follow that rule reference on the stack; this amounts to
+	/// computing FIRST of what follows the rule reference in the
+	/// enclosing rule. This local follow set only includes tokens
+	/// from within the rule; i.e., the FIRST computation done by
+	/// ANTLR stops at the end of a rule.
+	//
+	/// EXAMPLE
+	//
+	/// When you find a "no viable alt exception", the input is not
+	/// consistent with any of the alternatives for rule r.  The best
+	/// thing to do is to consume tokens until you see something that
+	/// can legally follow a call to r *or* any rule that called r.
+	/// You don't want the exact set of viable next tokens because the
+	/// input might just be missing a token--you might consume the
+	/// rest of the input looking for one of the missing tokens.
+	///
+	/// Consider grammar:
+	///
+	/// a : '[' b ']'
+	///   | '(' b ')'
+	///   ;
+	/// b : c '^' INT ;
+	/// c : ID
+	///   | INT
+	///   ;
+	///
+	/// At each rule invocation, the set of tokens that could follow
+	/// that rule is pushed on a stack.  Here are the various "local"
+	/// follow sets:
+	///
+	/// FOLLOW(b1_in_a) = FIRST(']') = ']'
+	/// FOLLOW(b2_in_a) = FIRST(')') = ')'
+	/// FOLLOW(c_in_b) = FIRST('^') = '^'
+	///
+	/// Upon erroneous input "[]", the call chain is
+	///
+	/// a -> b -> c
+	///
+	/// and, hence, the follow context stack is:
+	///
+	/// depth  local follow set     after call to rule
+	///   0         <EOF>                    a (from main())
+	///   1          ']'                     b
+	///   3          '^'                     c
+	///
+	/// Notice that ')' is not included, because b would have to have
+	/// been called from a different context in rule a for ')' to be
+	/// included.
+	///
+	/// For error recovery, we cannot consider FOLLOW(c)
+	/// (context-sensitive or otherwise).  We need the combined set of
+	/// all context-sensitive FOLLOW sets--the set of all tokens that
+	/// could follow any reference in the call chain.  We need to
+	/// resync to one of those tokens.  Note that FOLLOW(c)='^' and if
+	/// we resync'd to that token, we'd consume until EOF.  We need to
+	/// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
+	/// In this case, for input "[]", LA(1) is in this set so we would
+	/// not consume anything and after printing an error rule c would
+	/// return normally.  It would not find the required '^' though.
+	/// At this point, it gets a mismatched token error and throws an
+	/// exception (since LA(1) is not in the viable following token
+	/// set).  The rule exception handler tries to recover, but finds
+	/// the same recovery set and doesn't consume anything.  Rule b
+	/// exits normally returning to rule a.  Now it finds the ']' (and
+	/// with the successful match exits errorRecovery mode).
+	///
+	/// So, you can see that the parser walks up call chain looking
+	/// for the token that was a member of the recovery set.
+	///
+	/// Errors are not generated in errorRecovery mode.
+	///
+	/// ANTLR's error recovery mechanism is based upon original ideas:
+	///
+	/// "Algorithms + Data Structures = Programs" by Niklaus Wirth
+	///
+	/// and
+	///
+	/// "A note on error recovery in recursive descent parsers":
+	/// http://portal.acm.org/citation.cfm?id=947902.947905
+	///
+	/// Later, Josef Grosch had some good ideas:
+	///
+	/// "Efficient and Comfortable Error Recovery in Recursive Descent
+	/// Parsers":
+	/// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
+	///
+	/// Like Grosch I implemented local FOLLOW sets that are combined
+	/// at run-time upon error to avoid overhead during parsing.
+	///
+    BitsetType*	computeErrorRecoverySet();
+
+    /// Compute the context-sensitive FOLLOW set for current rule.
+	/// Documentation below is from the Java runtime.
+	///
+	/// This is the set of token types that can follow a specific rule
+	/// reference given a specific call chain.  You get the set of
+	/// viable tokens that can possibly come next (look ahead depth 1)
+	/// given the current call chain.  Contrast this with the
+	/// definition of plain FOLLOW for rule r:
+	///
+	///  FOLLOW(r)={x | S=>*alpha r beta in G and x in FIRST(beta)}
+	///
+	/// where x in T* and alpha, beta in V*; T is set of terminals and
+	/// V is the set of terminals and non terminals.  In other words,
+	/// FOLLOW(r) is the set of all tokens that can possibly follow
+	/// references to r in///any* sentential form (context).  At
+	/// runtime, however, we know precisely which context applies as
+	/// we have the call chain.  We may compute the exact (rather
+	/// than covering superset) set of following tokens.
+	///
+	/// For example, consider grammar:
+	///
+	/// stat : ID '=' expr ';'      // FOLLOW(stat)=={EOF}
+	///      | "return" expr '.'
+	///      ;
+	/// expr : atom ('+' atom)* ;   // FOLLOW(expr)=={';','.',')'}
+	/// atom : INT                  // FOLLOW(atom)=={'+',')',';','.'}
+	///      | '(' expr ')'
+	///      ;
+	///
+	/// The FOLLOW sets are all inclusive whereas context-sensitive
+	/// FOLLOW sets are precisely what could follow a rule reference.
+	/// For input input "i=(3);", here is the derivation:
+	///
+	/// stat => ID '=' expr ';'
+	///      => ID '=' atom ('+' atom)* ';'
+	///      => ID '=' '(' expr ')' ('+' atom)* ';'
+	///      => ID '=' '(' atom ')' ('+' atom)* ';'
+	///      => ID '=' '(' INT ')' ('+' atom)* ';'
+	///      => ID '=' '(' INT ')' ';'
+	///
+	/// At the "3" token, you'd have a call chain of
+	///
+	///   stat -> expr -> atom -> expr -> atom
+	///
+	/// What can follow that specific nested ref to atom?  Exactly ')'
+	/// as you can see by looking at the derivation of this specific
+	/// input.  Contrast this with the FOLLOW(atom)={'+',')',';','.'}.
+	///
+	/// You want the exact viable token set when recovering from a
+	/// token mismatch.  Upon token mismatch, if LA(1) is member of
+	/// the viable next token set, then you know there is most likely
+	/// a missing token in the input stream.  "Insert" one by just not
+	/// throwing an exception.
+	///
+    BitsetType*	computeCSRuleFollow();
+
+    /// Compute the current followset for the input stream.
+	///
+    BitsetType*	combineFollows(bool exact);
+
+    /// Attempt to recover from a single missing or extra token.
+	///
+	/// EXTRA TOKEN
+	///
+	/// LA(1) is not what we are looking for.  If LA(2) has the right token,
+	/// however, then assume LA(1) is some extra spurious token.  Delete it
+	/// and LA(2) as if we were doing a normal match(), which advances the
+	/// input.
+	///
+	/// MISSING TOKEN
+	///
+	/// If current token is consistent with what could come after
+	/// ttype then it is ok to "insert" the missing token, else throw
+	/// exception For example, Input "i=(3;" is clearly missing the
+	/// ')'.  When the parser returns from the nested call to expr, it
+	/// will have call chain:
+	///
+	///    stat -> expr -> atom
+	///
+	/// and it will be trying to match the ')' at this point in the
+	/// derivation:
+	///
+	///       => ID '=' '(' INT ')' ('+' atom)* ';'
+	///                          ^
+	/// match() will see that ';' doesn't match ')' and report a
+	/// mismatched token error.  To recover, it sees that LA(1)==';'
+	/// is in the set of tokens that can follow the ')' token
+	/// reference in rule atom.  It can assume that you forgot the ')'.
+	///
+	/// The exception that was passed in, in the java implementation is
+	/// sorted in the recognizer exception stack in the C version. To 'throw' it we set the
+	/// error flag and rules cascade back when this is set.
+	///
+    const UnitType* recoverFromMismatchedToken( ANTLR_UINT32	ttype, BitsetListType*	follow);
+
+    /** Function that recovers from a mismatched set in the token stream, in a similar manner
+     *  to (*recoverFromMismatchedToken)
+     */
+    const UnitType* recoverFromMismatchedSet(BitsetListType*	follow);
+
+    /** common routine to handle single token insertion for recovery functions.
+     */
+	/// This code is factored out from mismatched token and mismatched set
+	///  recovery.  It handles "single token insertion" error recovery for
+	/// both.  No tokens are consumed to recover from insertions.  Return
+	/// true if recovery was possible else return false.
+	///
+    bool	recoverFromMismatchedElement(BitsetListType*	follow);
+
+    /** function that consumes input until the next token matches
+     *  the given token.
+     */
+    void	consumeUntil(ANTLR_UINT32   tokenType);
+
+    /** function that consumes input until the next token matches
+     *  one in the given set.
+     */
+    void	consumeUntilSet(BitsetType*	set);
+
+    /** function that returns an ANTLR3_LIST of the strings that identify
+     *  the rules in the parser that got you to this point. Can be overridden by installing your
+     *	own function set.
+     *
+     * \todo Document how to override invocation stack functions.
+     */
+	StringStackType	getRuleInvocationStack();
+	StringStackType	getRuleInvocationStackNamed(ANTLR_UINT8*    name);
+
+    /** function that converts an ANLR3_LIST of tokens to an ANTLR3_LIST of
+     *  string token names. As this is mostly used in string template processing it may not be useful
+     *  in the C runtime.
+     */
+    StringListType	toStrings( const StringListType& );
+
+    /** function to return whether the rule has parsed input starting at the supplied
+     *  start index before. If the rule has not parsed input starting from the supplied start index,
+     *  then it will return ANTLR3_MEMO_RULE_UNKNOWN. If it has parsed from the suppled start point
+     *  then it will return the point where it last stopped parsing after that start point.
+     */
+    ANTLR_MARKER	getRuleMemoization( ANTLR_INTKEY	ruleIndex,
+												ANTLR_MARKER	ruleParseStart);
+
+    /** function that determines whether the rule has parsed input at the current index
+     *  in the input stream
+     */
+    bool	alreadyParsedRule(ANTLR_MARKER	ruleIndex);
+
+    /** Function that records whether the rule has parsed the input at a
+     *  current position successfully or not.
+     */
+    void	memoize(ANTLR_MARKER	ruleIndex,
+								ANTLR_MARKER	ruleParseStart);
+
+	/// Function that returns the current input symbol.
+    /// The is placed into any label for the associated token ref; e.g., x=ID.  Token
+	/// and tree parsers need to return different objects. Rather than test
+	/// for input stream type or change the IntStream interface, I use
+	/// a simple method to ask the recognizer to tell me what the current
+	/// input symbol is.
+	///
+	/// This is ignored for lexers and the lexer implementation of this
+	/// function should return NULL.
+	///
+	const UnitType*	getCurrentInputSymbol(IntStreamType* istream);
+	const UnitType*	getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<LexerType>);
+	const UnitType*	getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<ParserType>);
+	const UnitType*	getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<TreeParserType>);
+
+	/// Conjure up a missing token during error recovery.
+	///
+	/// The recognizer attempts to recover from single missing
+	/// symbols. But, actions might refer to that missing symbol.
+	/// For example, x=ID {f($x);}. The action clearly assumes
+	/// that there has been an identifier matched previously and that
+	/// $x points at that token. If that token is missing, but
+	/// the next token in the stream is what we want we assume that
+	/// this token is missing and we keep going. Because we
+	/// have to return some token to replace the missing token,
+	/// we have to conjure one up. This method gives the user control
+	/// over the tokens returned for missing tokens. Mostly,
+	/// you will want to create something special for identifier
+	/// tokens. For literals such as '{' and ',', the default
+	/// action in the parser or tree parser works. It simply creates
+	/// a CommonToken of the appropriate type. The text will be the token.
+	/// If you change what tokens must be created by the lexer,
+	/// override this method to create the appropriate tokens.
+	///
+	UnitType*	getMissingSymbol( IntStreamType*		istream, ExceptionBaseType*		e,
+												ANTLR_UINT32			expectedTokenType,
+												BitsetListType*		follow);
+
+    /** Function that returns whether the supplied grammar function
+     *  will parse the current input stream or not. This is the way that syntactic
+     *  predicates are evaluated. Unlike java, C is perfectly happy to invoke code
+     *  via a pointer to a function (hence that's what all the ANTLR3 C interfaces
+     *  do.
+     */
+	template<typename Predicate>
+    bool  synpred( ClassForwarder<Predicate> );
+
+	//In place of exConstruct, just directly instantiate the Exception Object
+
+    /** Reset the recognizer
+     */
+    void  reset();
+	void  reset( ClassForwarder<LexerType> );
+	template<typename CompType>
+	void  reset( ClassForwarder<CompType> );
+
+	void exConstruct();
+
+    ~BaseRecognizer();
+
+};
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3baserecognizer.inl"
+
+/// @}
+///
+
+#endif	    /* _ANTLR3_BASERECOGNIZER_H	*/
+
diff --git a/runtime/Cpp/include/antlr3baserecognizer.inl b/runtime/Cpp/include/antlr3baserecognizer.inl
new file mode 100755
index 0000000..5d5acbf
--- /dev/null
+++ b/runtime/Cpp/include/antlr3baserecognizer.inl
@@ -0,0 +1,919 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template< class ImplTraits, class StreamType >
+BaseRecognizer<ImplTraits, StreamType>::BaseRecognizer(ANTLR_UINT32 sizeHint,
+											RecognizerSharedStateType* state)
+{
+	m_debugger = NULL;
+
+	// If we have been supplied with a pre-existing recognizer state
+	// then we just install it, otherwise we must create one from scratch
+	//
+	if	(state == NULL)
+	{
+		m_state = new RecognizerSharedStateType();
+		m_state->set_sizeHint( sizeHint );
+	}
+	else
+	{
+		// Install the one we were given, and do not reset it here
+		// as it will either already have been initialized or will
+		// be in a state that needs to be preserved.
+		//
+		m_state = state;
+	}
+}
+
+template< class ImplTraits, class StreamType >
+ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::SuperType* BaseRecognizer<ImplTraits, StreamType>::get_super()
+{
+	return static_cast<SuperType*>(this);
+}
+
+template< class ImplTraits, class StreamType >
+ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::RecognizerSharedStateType* BaseRecognizer<ImplTraits, StreamType>::get_state() const
+{
+	return m_state;
+}
+template< class ImplTraits, class StreamType >
+ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::DebugEventListenerType* BaseRecognizer<ImplTraits, StreamType>::get_debugger() const
+{
+	return m_debugger;
+}
+template< class ImplTraits, class StreamType >
+ANTLR_INLINE void BaseRecognizer<ImplTraits, StreamType>::set_state( RecognizerSharedStateType* state )
+{
+	m_state = state;
+}
+template< class ImplTraits, class StreamType >
+ANTLR_INLINE void BaseRecognizer<ImplTraits, StreamType>::set_debugger( DebugEventListenerType* debugger )
+{
+	m_debugger = debugger;
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* 
+BaseRecognizer<ImplTraits, StreamType>::match(ANTLR_UINT32 ttype, BitsetListType* follow)
+{
+	SuperType*  super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_istream();
+
+	// Pick up the current input token/node for assignment to labels
+	//
+	const UnitType* matchedSymbol = this->getCurrentInputSymbol(is);
+
+    if	(is->_LA(1) == ttype)
+    {
+		// The token was the one we were told to expect
+		//
+		is->consume();					   // Consume that token from the stream
+		m_state->set_errorRecovery(false); // Not in error recovery now (if we were)
+		m_state->set_failed(false);	// The match was a success
+		return matchedSymbol;								// We are done
+    }
+
+    // We did not find the expected token type, if we are backtracking then
+    // we just set the failed flag and return.
+    //
+    if	( m_state->get_backtracking() > 0)
+    {
+		// Backtracking is going on
+		//
+		m_state->set_failed(true);
+		return matchedSymbol;
+	}
+
+    // We did not find the expected token and there is no backtracking
+    // going on, so we mismatch, which creates an exception in the recognizer exception
+    // stack.
+    //
+	matchedSymbol = this->recoverFromMismatchedToken(ttype, follow);
+    return matchedSymbol;
+
+}
+
+template< class ImplTraits, class StreamType >
+void BaseRecognizer<ImplTraits, StreamType>::matchAny()
+{
+	SuperType*  super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_istream();
+
+	is->consume();
+	m_state->set_errorRecovery(false);
+	m_state->set_failed(false);
+    return;
+}
+
+template< class ImplTraits, class StreamType >
+bool BaseRecognizer<ImplTraits, StreamType>::mismatchIsUnwantedToken(IntStreamType* is, ANTLR_UINT32 ttype)
+{
+	ANTLR_UINT32 nextt = is->_LA(2);
+
+	if	(nextt == ttype)
+	{
+		if(m_state->get_exception() != NULL)
+			m_state->get_exception()->set_expecting(nextt);
+		return true;		// This token is unknown, but the next one is the one we wanted
+	}
+	else
+		return false;	// Neither this token, nor the one following is the one we wanted
+}
+
+template< class ImplTraits, class StreamType >
+bool BaseRecognizer<ImplTraits, StreamType>::mismatchIsMissingToken(IntStreamType* is, BitsetListType* follow)
+{
+	bool	retcode;
+	BitsetType*	followClone;
+	BitsetType*	viableTokensFollowingThisRule;
+
+	if	(follow == NULL)
+	{
+		// There is no information about the tokens that can follow the last one
+		// hence we must say that the current one we found is not a member of the
+		// follow set and does not indicate a missing token. We will just consume this
+		// single token and see if the parser works it out from there.
+		//
+		return	false;
+	}
+
+	followClone						= NULL;
+	viableTokensFollowingThisRule	= NULL;
+
+	// The C bitset maps are laid down at compile time by the
+	// C code generation. Hence we cannot remove things from them
+	// and so on. So, in order to remove EOR (if we need to) then
+	// we clone the static bitset.
+	//
+	followClone = follow->bitsetLoad();
+	if	(followClone == NULL)
+		return false;
+
+	// Compute what can follow this grammar reference
+	//
+	if	(followClone->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE))
+	{
+		// EOR can follow, but if we are not the start symbol, we
+		// need to remove it.
+		//
+		followClone->remove(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE);
+
+		// Now compute the visiable tokens that can follow this rule, according to context
+		// and make them part of the follow set.
+		//
+		viableTokensFollowingThisRule = this->computeCSRuleFollow();
+		followClone->borInPlace(viableTokensFollowingThisRule);
+	}
+
+	/// if current token is consistent with what could come after set
+	/// then we know we're missing a token; error recovery is free to
+	/// "insert" the missing token
+	///
+	/// BitSet cannot handle negative numbers like -1 (EOF) so I leave EOR
+	/// in follow set to indicate that the fall of the start symbol is
+	/// in the set (EOF can follow).
+	///
+	if	(		followClone->isMember(is->_LA(1))
+			||	followClone->isMember(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE)
+		)
+	{
+		retcode = true;
+	}
+	else
+	{
+		retcode	= false;
+	}
+
+	if	(viableTokensFollowingThisRule != NULL)
+	{
+		delete viableTokensFollowingThisRule;
+	}
+	if	(followClone != NULL)
+	{
+		delete followClone;
+	}
+
+	return retcode;
+}
+
+template< class ImplTraits, class StreamType >
+void BaseRecognizer<ImplTraits, StreamType>::mismatch(ANTLR_UINT32 ttype, BitsetListType* follow)
+{
+	this->get_super()->mismatch( ttype, follow );
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::reportError()
+{
+	this->reportError( ClassForwarder<SuperType>() );
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::reportError( ClassForwarder<LexerType> )
+{
+	// Indicate this recognizer had an error while processing.
+	//
+	m_state->inc_errorCount();
+
+    this->displayRecognitionError(m_state->get_tokenNames());
+}
+
+template< class ImplTraits, class StreamType >
+template<typename CompType>
+void	BaseRecognizer<ImplTraits, StreamType>::reportError(ClassForwarder<CompType> )
+{
+	    // Invoke the debugger event if there is a debugger listening to us
+	//
+	if	( m_debugger != NULL)
+	{
+		m_debugger->recognitionException( m_state->get_exception() );
+	}
+
+    if	( m_state->get_errorRecovery() == true)
+    {
+		// Already in error recovery so don't display another error while doing so
+		//
+		return;
+    }
+
+    // Signal we are in error recovery now
+    //
+    m_state->set_errorRecovery(true);
+
+	// Indicate this recognizer had an error while processing.
+	//
+	m_state->inc_errorCount();
+
+	// Call the error display routine
+	//
+    this->displayRecognitionError( m_state->get_tokenNames() );
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::displayRecognitionError(ANTLR_UINT8** tokenNames)
+{
+	// Retrieve some info for easy reading.
+	//
+	ExceptionBaseType* ex	    =		m_state->get_exception();
+	StringType ttext;
+
+	// See if there is a 'filename' we can use
+	//
+	SuperType* super = static_cast<SuperType*>(this);
+	super->displayRecognitionError(tokenNames, ex);
+}
+
+template< class ImplTraits, class StreamType >
+ANTLR_UINT32 BaseRecognizer<ImplTraits, StreamType>::getNumberOfSyntaxErrors()
+{
+	return	m_state->get_errorCount();
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::recover()
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+	// Are we about to repeat the same error?
+	//
+    if	( m_state->get_lastErrorIndex() == is->index())
+    {
+		// The last error was at the same token index point. This must be a case
+		// where LT(1) is in the recovery token set so nothing is
+		// consumed. Consume a single token so at least to prevent
+		// an infinite loop; this is a failsafe.
+		//
+		is->consume();
+    }
+
+    // Record error index position
+    //
+    m_state->set_lastErrorIndex( is->index() );
+
+    // Work out the follows set for error recovery
+    //
+    BitsetType* followSet	= this->computeErrorRecoverySet();
+
+    // Call resync hook (for debuggers and so on)
+    //
+    this->beginResync();
+
+    // Consume tokens until we have resynced to something in the follows set
+    //
+    this->consumeUntilSet(followSet);
+
+    // End resync hook
+    //
+    this->endResync();
+
+    // Destroy the temporary bitset we produced.
+    //
+    delete followSet;
+
+    // Reset the inError flag so we don't re-report the exception
+    //
+    m_state->set_error(false);
+    m_state->set_failed(false);
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::beginResync()
+{
+	if	(m_debugger != NULL)
+	{
+		m_debugger->beginResync();
+	}
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::endResync()
+{
+	if	(m_debugger != NULL)
+	{
+		m_debugger->endResync();
+	}
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::beginBacktrack(ANTLR_UINT32 level)
+{
+	if	(m_debugger != NULL)
+	{
+		m_debugger->beginBacktrack(level);
+	}
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::endBacktrack(ANTLR_UINT32 level, bool successful)
+{
+	if	(m_debugger != NULL)
+	{
+		m_debugger->endBacktrack(level);
+	}
+}
+
+template< class ImplTraits, class StreamType >
+typename BaseRecognizer<ImplTraits, StreamType>::BitsetType*	BaseRecognizer<ImplTraits, StreamType>::computeErrorRecoverySet()
+{
+	return   this->combineFollows(false);
+}
+
+template< class ImplTraits, class StreamType >
+typename BaseRecognizer<ImplTraits, StreamType>::BitsetType*	BaseRecognizer<ImplTraits, StreamType>::computeCSRuleFollow()
+{
+	return   this->combineFollows(false);
+}
+
+template< class ImplTraits, class StreamType >
+typename BaseRecognizer<ImplTraits, StreamType>::BitsetType*	BaseRecognizer<ImplTraits, StreamType>::combineFollows(bool exact)
+{
+	BitsetType*	followSet;
+    BitsetType*	localFollowSet;
+    ANTLR_UINT32	top;
+    ANTLR_UINT32	i;
+
+    top	= static_cast<ANTLR_UINT32>( m_state->get_following().size() );
+
+    followSet	    = new BitsetType(0);
+	localFollowSet	= NULL;
+
+    for (i = top; i>0; i--)
+    {
+		localFollowSet =  m_state->get_following().at(i-1).bitsetLoad();
+
+		if  (localFollowSet != NULL)
+		{
+			followSet->borInPlace(localFollowSet);
+
+			if	(exact == true)
+			{
+				if	(localFollowSet->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE) == false)
+				{
+					// Only leave EOR in the set if at top (start rule); this lets us know
+					// if we have to include the follow(start rule); I.E., EOF
+					//
+					if	(i>1)
+					{
+						followSet->remove(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE);
+					}
+				}
+				else
+				{
+					break;	// Cannot see End Of Rule from here, just drop out
+				}
+			}
+			delete localFollowSet;
+			localFollowSet = NULL;
+		}
+    }
+
+	if	(localFollowSet != NULL)
+	{
+		delete localFollowSet;
+	}
+    return  followSet;
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* 
+BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedToken( ANTLR_UINT32	ttype, BitsetListType*	follow)
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+	const UnitType* matchedSymbol;
+
+	// If the next token after the one we are looking at in the input stream
+	// is what we are looking for then we remove the one we have discovered
+	// from the stream by consuming it, then consume this next one along too as
+	// if nothing had happened.
+	//
+	if	( this->mismatchIsUnwantedToken( is, ttype) == true)
+	{
+		// Create an exception if we need one
+		//
+		new ANTLR_Exception<ImplTraits, UNWANTED_TOKEN_EXCEPTION, StreamType>(this, "");
+
+		// Call resync hook (for debuggers and so on)
+		//
+		if	(m_debugger != NULL)
+		{
+			m_debugger->beginResync();
+		}
+
+		// "delete" the extra token
+		//
+		this->beginResync();
+		is->consume();
+		this->endResync();
+		// End resync hook
+		//
+		if	(m_debugger != NULL)
+		{
+			m_debugger->endResync();
+		}
+
+		// Print out the error after we consume so that ANTLRWorks sees the
+		// token in the exception.
+		//
+		this->reportError();
+
+		// Return the token we are actually matching
+		//
+		matchedSymbol = this->getCurrentInputSymbol(is);
+
+		// Consume the token that the rule actually expected to get as if everything
+		// was hunky dory.
+		//
+		is->consume();
+
+		m_state->set_error(false); // Exception is not outstanding any more
+
+		return	matchedSymbol;
+	}
+
+	// Single token deletion (Unwanted above) did not work
+	// so we see if we can insert a token instead by calculating which
+	// token would be missing
+	//
+	if	( this->mismatchIsMissingToken(is, follow))
+	{
+		// We can fake the missing token and proceed
+		//
+		new ANTLR_Exception<ImplTraits, MISSING_TOKEN_EXCEPTION, StreamType>(this, "");
+		matchedSymbol = this->getMissingSymbol( is, m_state->get_exception(), ttype, follow);
+		m_state->get_exception()->set_token( matchedSymbol );
+		m_state->get_exception()->set_expecting(ttype);
+
+		// Print out the error after we insert so that ANTLRWorks sees the
+		// token in the exception.
+		//
+		this->reportError();
+
+		m_state->set_error(false);	// Exception is not outstanding any more
+
+		return	matchedSymbol;
+	}
+
+	// Create an exception if we need one
+	//
+	new ANTLR_Exception<ImplTraits, RECOGNITION_EXCEPTION, StreamType>(this, "");
+
+	// Neither deleting nor inserting tokens allows recovery
+	// must just report the exception.
+	//
+	m_state->set_error(true);
+	return NULL;
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* 
+BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedSet(BitsetListType*	follow)
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+	const UnitType* matchedSymbol;
+
+	if	(this->mismatchIsMissingToken(is, follow) == true)
+	{
+		// We can fake the missing token and proceed
+		//
+		new ANTLR_Exception<ImplTraits, MISSING_TOKEN_EXCEPTION, StreamType>(this);
+		matchedSymbol = this->getMissingSymbol(is, m_state->get_exception(), follow);
+		m_state->get_exception()->set_token(matchedSymbol);
+
+		// Print out the error after we insert so that ANTLRWorks sees the
+		// token in the exception.
+		//
+		this->reportError();
+
+		m_state->set_error(false);	// Exception is not outstanding any more
+
+		return	matchedSymbol;
+	}
+
+    // TODO - Single token deletion like in recoverFromMismatchedToken()
+    //
+    m_state->set_error(true);
+	m_state->set_failed(true);
+	return NULL;
+}
+
+template< class ImplTraits, class StreamType >
+bool  BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedElement(BitsetListType*	followBits)
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+
+	BitsetType* follow	= followBits->load();
+	BitsetType*   viableToksFollowingRule;
+
+    if	(follow == NULL)
+    {
+		/* The follow set is NULL, which means we don't know what can come
+		 * next, so we "hit and hope" by just signifying that we cannot
+		 * recover, which will just cause the next token to be consumed,
+		 * which might dig us out.
+		 */
+		return	false;
+    }
+
+    /* We have a bitmap for the follow set, hence we can compute
+     * what can follow this grammar element reference.
+     */
+    if	(follow->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE) == true)
+    {
+		/* First we need to know which of the available tokens are viable
+		 * to follow this reference.
+		 */
+		viableToksFollowingRule	= this->computeCSRuleFollow();
+
+		/* Remove the EOR token, which we do not wish to compute with
+		 */
+		follow->remove( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE);
+		delete viableToksFollowingRule;
+		/* We now have the computed set of what can follow the current token
+		 */
+    }
+
+    /* We can now see if the current token works with the set of tokens
+     * that could follow the current grammar reference. If it looks like it
+     * is consistent, then we can "insert" that token by not throwing
+     * an exception and assuming that we saw it.
+     */
+    if	( follow->isMember(is->_LA(1)) == true)
+    {
+		/* report the error, but don't cause any rules to abort and stuff
+		 */
+		this->reportError();
+		if	(follow != NULL)
+		{
+			delete follow;
+		}
+		m_state->set_error(false);
+		m_state->set_failed(false);
+		return true;	/* Success in recovery	*/
+    }
+
+    if	(follow != NULL)
+    {
+		delete follow;
+    }
+
+    /* We could not find anything viable to do, so this is going to
+     * cause an exception.
+     */
+    return  false;
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::consumeUntil(ANTLR_UINT32   tokenType)
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+
+	// What do have at the moment?
+    //
+    ANTLR_UINT32 ttype	= is->_LA(1);
+
+    // Start eating tokens until we get to the one we want.
+    //
+    while   (ttype != ImplTraits::CommonTokenType::TOKEN_EOF && ttype != tokenType)
+    {
+		is->consume();
+		ttype	= is->_LA(1);
+    }
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::consumeUntilSet(BitsetType*	set)
+{
+    ANTLR_UINT32	    ttype;
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_parser_istream();
+
+    // What do have at the moment?
+    //
+    ttype	= is->_LA(1);
+
+    // Start eating tokens until we get to one we want.
+    //
+    while   (ttype != ImplTraits::CommonTokenType::TOKEN_EOF && set->isMember(ttype) == false)
+    {
+		is->consume();
+		ttype	= is->_LA(1);
+    }
+
+}
+
+template< class ImplTraits, class StreamType >
+ANTLR_MARKER	BaseRecognizer<ImplTraits, StreamType>::getRuleMemoization( ANTLR_INTKEY	ruleIndex, ANTLR_MARKER	ruleParseStart)
+{
+	/* The rule memos are an ANTLR3_LIST of ANTLR3_LIST.
+     */
+	typedef IntTrie<ImplTraits, ANTLR_MARKER> RuleListType;
+	typedef TrieEntry<ImplTraits, RuleListType*> EntryType;
+	typedef TrieEntry<ImplTraits, ANTLR_MARKER> SubEntryType;
+    ANTLR_MARKER	stopIndex;
+    EntryType*	entry;
+
+    /* See if we have a list in the ruleMemos for this rule, and if not, then create one
+     * as we will need it eventually if we are being asked for the memo here.
+     */
+    entry	= m_state->get_ruleMemo()->get(ruleIndex);
+
+    if	(entry == NULL)
+    {
+		/* Did not find it, so create a new one for it, with a bit depth based on the
+		 * size of the input stream. We need the bit depth to incorporate the number if
+		 * bits required to represent the largest possible stop index in the input, which is the
+		 * last character. An int stream is free to return the largest 64 bit offset if it has
+		 * no idea of the size, but you should remember that this will cause the leftmost
+		 * bit match algorithm to run to 63 bits, which will be the whole time spent in the trie ;-)
+		 */
+		m_state->get_ruleMemo()->add( ruleIndex, new RuleListType(63) );
+
+		/* We cannot have a stopIndex in a trie we have just created of course
+		 */
+		return	MEMO_RULE_UNKNOWN;
+    }
+
+    RuleListType* ruleList	= entry->get_data();
+
+    /* See if there is a stop index associated with the supplied start index.
+     */
+    stopIndex	= 0;
+
+    SubEntryType* sub_entry = ruleList->get(ruleParseStart);
+    if (sub_entry != NULL)
+    {
+		stopIndex = sub_entry->get_data();
+    }
+
+    if	(stopIndex == 0)
+    {
+		return MEMO_RULE_UNKNOWN;
+    }
+
+    return  stopIndex;
+}
+
+template< class ImplTraits, class StreamType >
+bool	BaseRecognizer<ImplTraits, StreamType>::alreadyParsedRule(ANTLR_MARKER	ruleIndex)
+{
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_istream();
+
+    /* See if we have a memo marker for this.
+     */
+    ANTLR_MARKER stopIndex	    = this->getRuleMemoization( ruleIndex, is->index() );
+
+    if	(stopIndex  == MEMO_RULE_UNKNOWN)
+    {
+		return false;
+    }
+
+    if	(stopIndex == MEMO_RULE_FAILED)
+    {
+		m_state->set_failed(true);
+    }
+    else
+    {
+		is->seek(stopIndex+1);
+    }
+
+    /* If here then the rule was executed for this input already
+     */
+    return  true;
+}
+
+template< class ImplTraits, class StreamType >
+void	BaseRecognizer<ImplTraits, StreamType>::memoize(ANTLR_MARKER ruleIndex, ANTLR_MARKER ruleParseStart)
+{
+   /* The rule memos are an ANTLR3_LIST of ANTLR3_LIST.
+    */
+	typedef IntTrie<ImplTraits, ANTLR_MARKER> RuleListType;
+	typedef TrieEntry<ImplTraits, RuleListType*> EntryType;
+    EntryType*	    entry;
+    ANTLR_MARKER	    stopIndex;
+	SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_istream();
+
+    stopIndex	= (m_state->get_failed() == true) ? MEMO_RULE_FAILED : is->index() - 1;
+
+    entry	= m_state->get_ruleMemo()->get(ruleIndex);
+
+    if	(entry != NULL)
+    {
+		RuleListType*	ruleList = entry->get_data();
+
+		/* If we don't already have this entry, append it. The memoize trie does not
+		 * accept duplicates so it won't add it if already there and we just ignore the
+		 * return code as we don't care if it is there already.
+		 */
+		ruleList->add(ruleParseStart, stopIndex);
+    }
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType*
+BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol( IntStreamType* istream )
+{
+	return this->getCurrentInputSymbol( istream, ClassForwarder<SuperType>() );
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType*
+BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<LexerType>)
+{
+	return NULL;
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType*
+BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<ParserType>)
+{
+	typedef typename ImplTraits::TokenStreamType TokenStreamType;
+	TokenStreamType* token_stream = static_cast<TokenStreamType*>(istream);
+	return token_stream->_LT(1);
+}
+
+template< class ImplTraits, class StreamType >
+const typename BaseRecognizer<ImplTraits, StreamType>::UnitType*
+BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<TreeParserType>)
+{
+	typedef typename ImplTraits::TreeNodeStreamType TreeNodeStreamType;
+	TreeNodeStreamType*	ctns = static_cast<TreeNodeStreamType*>(istream);
+	return ctns->_LT(1);
+}
+
+
+template< class ImplTraits, class StreamType >
+typename BaseRecognizer<ImplTraits, StreamType>::UnitType*	BaseRecognizer<ImplTraits, StreamType>::getMissingSymbol( IntStreamType* istream,
+										  ExceptionBaseType*		e,
+										  ANTLR_UINT32			expectedTokenType,
+										  BitsetListType*	follow)
+{
+	return this->get_super()->getMissingSymbol( istream, e, expectedTokenType, follow );
+}
+
+
+template< class ImplTraits, class StreamType >
+	template<typename Predicate>
+bool  BaseRecognizer<ImplTraits, StreamType>::synpred(ClassForwarder<Predicate> pred)
+{
+	ANTLR_MARKER   start;
+    SuperType* super = static_cast<SuperType*>(this);
+	IntStreamType* is = super->get_istream();
+
+    /* Begin backtracking so we can get back to where we started after trying out
+     * the syntactic predicate.
+     */
+    start   = is->mark();
+    m_state->inc_backtracking();
+
+    /* Try the syntactical predicate
+     */
+    this->get_super()->synpred( pred );
+
+    /* Reset
+     */
+    is->rewind(start);
+    m_state->dec_backtracking();
+
+    if	( m_state->get_failed() == true)
+    {
+		/* Predicate failed
+		 */
+		m_state->set_failed(false);
+		return	false;
+    }
+    else
+    {
+		/* Predicate was successful
+		 */
+		m_state->set_failed(false);
+		return	true;
+    }
+}
+
+template< class ImplTraits, class StreamType >
+void BaseRecognizer<ImplTraits, StreamType>::exConstruct()
+{
+	this->get_super()->exConstruct();
+}
+
+template< class ImplTraits, class StreamType >
+void  BaseRecognizer<ImplTraits, StreamType>::reset()
+{
+	this->reset( ClassForwarder<SuperType>() );
+}
+
+template< class ImplTraits, class StreamType >
+template< typename CompType >
+void  BaseRecognizer<ImplTraits, StreamType>::reset( ClassForwarder<CompType> )
+{
+	typedef typename RecognizerSharedStateType::RuleMemoType RuleMemoType;
+	 m_state->get_following().clear();
+
+	// Reset the state flags
+	//
+	m_state->set_errorRecovery(false);
+	m_state->set_lastErrorIndex(-1);
+	m_state->set_failed(false);
+	m_state->set_errorCount(0);
+	m_state->set_backtracking(0);
+
+	if	(m_state->get_ruleMemo() != NULL)
+	{
+		delete m_state->get_ruleMemo();
+		m_state->set_ruleMemo( new RuleMemoType(15) );	/* 16 bit depth is enough for 32768 rules! */
+	}
+}
+
+template< class ImplTraits, class StreamType >
+void  BaseRecognizer<ImplTraits, StreamType>::reset( ClassForwarder<LexerType> )
+{
+	m_state->set_token_present( false );
+    m_state->set_type( ImplTraits::CommonTokenType::TOKEN_INVALID );
+    m_state->set_channel( TOKEN_DEFAULT_CHANNEL );
+    m_state->set_tokenStartCharIndex( -1 );
+    m_state->set_tokenStartCharPositionInLine(-1);
+    m_state->set_tokenStartLine( -1 );
+    m_state->set_text("");
+}
+
+template< class ImplTraits, class StreamType >
+BaseRecognizer<ImplTraits, StreamType>::~BaseRecognizer()
+{
+	// Did we have a state allocated?
+	//
+	if	(m_state != NULL)
+	{
+		// Free any rule memoization we set up
+		//
+		if	(m_state->get_ruleMemo() != NULL)
+		{
+			delete m_state->get_ruleMemo();
+			m_state->set_ruleMemo(NULL);
+		}
+
+
+		// Free any exception space we have left around
+		//
+		ExceptionBaseType* thisE = m_state->get_exception();
+		if	(thisE != NULL)
+		{
+			delete thisE;
+		}
+
+		// Free the shared state memory
+		//
+		delete m_state;
+	}
+
+	// Free the actual recognizer space
+	//
+}
+
+
+
+ANTLR_END_NAMESPACE()
diff --git a/runtime/Cpp/include/antlr3bitset.hpp b/runtime/Cpp/include/antlr3bitset.hpp
new file mode 100755
index 0000000..a711b8a
--- /dev/null
+++ b/runtime/Cpp/include/antlr3bitset.hpp
@@ -0,0 +1,224 @@
+/**
+ * \file
+ * Defines the basic structures of an ANTLR3 bitset. this is a C version of the 
+ * cut down Bitset class provided with the java version of antlr 3.
+ * 
+ * 
+ */
+#ifndef	_ANTLR3_BITSET_HPP
+#define	_ANTLR3_BITSET_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    "antlr3defs.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+/** How many bits in the elements
+ */
+static const ANTLR_UINT32	ANTLR_BITSET_BITS =	64;
+
+/** How many bits in a nible of bits
+ */
+static const ANTLR_UINT32	ANTLR_BITSET_NIBBLE	= 4;
+
+/** log2 of ANTLR3_BITSET_BITS 2^ANTLR3_BITSET_LOG_BITS = ANTLR3_BITSET_BITS
+ */
+static const ANTLR_UINT32	ANTLR_BITSET_LOG_BITS =	6;
+
+/** We will often need to do a mod operator (i mod nbits).
+ *  For powers of two, this mod operation is the
+ *  same as:
+ *   - (i & (nbits-1)).  
+ *
+ * Since mod is relatively slow, we use an easily
+ * precomputed mod mask to do the mod instead.
+ */
+static const ANTLR_UINT32	ANTLR_BITSET_MOD_MASK = ANTLR_BITSET_BITS - 1;
+
+template <class ImplTraits>
+class BitsetList : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::AllocPolicyType AllocPolicyType;
+	typedef typename ImplTraits::BitsetType BitsetType;
+
+private:
+	/// Pointer to the allocated array of bits for this bit set, which
+    /// is an array of 64 bit elements (of the architecture). If we find a 
+    /// machine/C compiler that does not know anything about 64 bit values
+    ///	then it should be easy enough to produce a 32 bit (or less) version
+    /// of the bitset code. Note that the pointer here may be static if laid down
+	/// by the code generation, and it must be copied if it is to be manipulated
+	/// to perform followset calculations.
+    ///
+    ANTLR_BITWORD*  m_bits;
+
+    /// Length of the current bit set in ANTLR3_UINT64 units.
+    ///
+    ANTLR_UINT32    m_length;
+
+public:
+	BitsetList();
+	BitsetList( ANTLR_BITWORD* bits, ANTLR_UINT32 length );
+
+	ANTLR_BITWORD* get_bits() const;
+	ANTLR_UINT32 get_length() const;
+	void set_bits( ANTLR_BITWORD* bits );
+	void set_length( ANTLR_UINT32 length );
+
+	///
+	/// \brief
+	/// Creates a new bitset with at least one 64 bit bset of bits, but as
+	/// many 64 bit sets as are required.
+	///
+	/// \param[in] bset
+	/// A variable number of bits to add to the set, ending in -1 (impossible bit).
+	/// 
+	/// \returns
+	/// A new bit set with all of the specified bitmaps in it and the API
+	/// initialized.
+	/// 
+	/// Call as:
+	///  - pANTLR3_BITSET = antlrBitsetLoad(bset, bset11, ..., -1);
+	///  - pANTLR3_BITSET = antlrBitsetOf(-1);  Create empty bitset 
+	///
+	/// \remarks
+	/// Stdargs function - must supply -1 as last paremeter, which is NOT
+	/// added to the set.
+	/// 
+	///
+	BitsetType* bitsetLoad();
+
+	BitsetType* bitsetCopy();
+
+};
+
+template <class ImplTraits>
+class Bitset : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::AllocPolicyType AllocPolicyType;
+	typedef typename AllocPolicyType::template ListType<ANTLR_UINT32> IntListType;
+	typedef typename ImplTraits::BitsetListType BitsetListType;
+
+private:
+	/// The actual bits themselves
+	///
+	BitsetListType		m_blist;
+
+public:
+	Bitset( ANTLR_UINT32 nbits=0 );
+	Bitset( const Bitset& bitset );
+    Bitset*  clone() const;
+	Bitset*  bor(Bitset* bitset2);
+
+	BitsetListType& get_blist();
+	void	 borInPlace(Bitset* bitset2);
+	ANTLR_UINT32 size() const;
+	void	add(ANTLR_INT32 bit);
+	void	grow(ANTLR_INT32 newSize);
+	bool	equals(Bitset* bitset2) const;
+	bool	isMember(ANTLR_UINT32 bit) const;
+	ANTLR_UINT32 numBits() const;
+	void remove(ANTLR_UINT32 bit);
+	bool isNilNode() const;
+
+	/** Produce an integer list of all the bits that are turned on
+	 *  in this bitset. Used for error processing in the main as the bitset
+	 *  reresents a number of integer tokens which we use for follow sets
+	 *  and so on.
+	 *
+	 *  The first entry is the number of elements following in the list.
+	 */
+	ANTLR_INT32* toIntList() const;
+
+	///
+	/// \brief
+	/// Creates a new bitset with at least one element, but as
+	/// many elements are required.
+	/// 
+	/// \param[in] bit
+	/// A variable number of bits to add to the set, ending in -1 (impossible bit).
+	/// 
+	/// \returns
+	/// A new bit set with all of the specified elements added into it.
+	/// 
+	/// Call as:
+	///  - pANTLR3_BITSET = antlrBitsetOf(n, n1, n2, -1);
+	///  - pANTLR3_BITSET = antlrBitsetOf(-1);  Create empty bitset 
+	///
+	/// \remarks
+	/// Stdargs function - must supply -1 as last paremeter, which is NOT
+	/// added to the set.
+	/// 
+	///
+	//C++ doesn't like variable length arguments. so use function overloading
+	static Bitset* BitsetOf(ANTLR_INT32 bit);
+	static Bitset* BitsetOf(ANTLR_INT32 bit1, ANTLR_INT32 bit2);
+	
+	///
+	/// \brief
+	/// Creates a new bitset with at least one 64 bit bset of bits, but as
+	/// many 64 bit sets as are required.
+	///
+	/// \param[in] bset
+	/// A variable number of bits to add to the set, ending in -1 (impossible bit).
+	/// 
+	/// \returns
+	/// A new bit set with all of the specified bitmaps in it and the API
+	/// initialized.
+	/// 
+	/// Call as:
+	///  - pANTLR3_BITSET = antlrBitsetLoad(bset, bset11, ..., -1);
+	///  - pANTLR3_BITSET = antlrBitsetOf(-1);  Create empty bitset 
+	///
+	/// \remarks
+	/// Stdargs function - must supply -1 as last paremeter, which is NOT
+	/// added to the set.
+	/// 
+	///antlr3BitsetList
+	static Bitset*  BitsetFromList(const IntListType& list);
+	~Bitset();
+
+private:
+	void	growToInclude(ANTLR_INT32 bit);
+	static ANTLR_UINT64	BitMask(ANTLR_UINT32 bitNumber);
+	static ANTLR_UINT32	NumWordsToHold(ANTLR_UINT32 bit);
+	static ANTLR_UINT32	WordNumber(ANTLR_UINT32 bit);
+	void bitsetORInPlace(Bitset* bitset2);
+	
+};
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3bitset.inl"
+
+#endif
+
diff --git a/runtime/Cpp/include/antlr3bitset.inl b/runtime/Cpp/include/antlr3bitset.inl
new file mode 100755
index 0000000..ad2f620
--- /dev/null
+++ b/runtime/Cpp/include/antlr3bitset.inl
@@ -0,0 +1,492 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template <class ImplTraits>
+ANTLR_INLINE BitsetList<ImplTraits>::BitsetList()
+{
+	m_bits = NULL;
+	m_length  = 0;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE BitsetList<ImplTraits>::BitsetList( ANTLR_BITWORD* bits, ANTLR_UINT32 length )
+{
+	m_bits = bits;
+	m_length  = length;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_BITWORD* BitsetList<ImplTraits>::get_bits() const
+{
+	return m_bits;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32 BitsetList<ImplTraits>::get_length() const
+{
+	return m_length;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE void BitsetList<ImplTraits>::set_bits( ANTLR_BITWORD* bits )
+{
+	m_bits = bits;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE void BitsetList<ImplTraits>::set_length( ANTLR_UINT32 length )
+{
+	m_length = length;
+}
+
+template <class ImplTraits>
+typename BitsetList<ImplTraits>::BitsetType* BitsetList<ImplTraits>::bitsetLoad()
+{
+	// Allocate memory for the bitset structure itself
+	// the input parameter is the bit number (0 based)
+	// to include in the bitset, so we need at at least
+	// bit + 1 bits. If any arguments indicate a 
+	// a bit higher than the default number of bits (0 means default size)
+	// then Add() will take care
+	// of it.
+	//
+	BitsetType* bitset  = new BitsetType();
+
+	if	(this != NULL)
+	{
+		// Now we can add the element bits into the set
+		//
+		ANTLR_UINT32 count=0;
+		while (count < m_length)
+		{
+			if( bitset->get_blist().get_length() <= count)
+				bitset->grow(count+1);
+
+			typename ImplTraits::BitsetListType& blist = bitset->get_blist();
+			blist.m_bits[count] = *(m_bits+count);
+			count++;
+		}
+	}
+
+	// return the new bitset
+	//
+	return  bitset;
+}
+
+template <class ImplTraits>
+typename BitsetList<ImplTraits>::BitsetType* BitsetList<ImplTraits>::bitsetCopy()
+{
+	BitsetType*  bitset;
+	ANTLR_UINT32 numElements = m_length;
+
+    // Avoid memory thrashing at the expense of a few more bytes
+    //
+    if	(numElements < 8)
+		numElements = 8;
+
+    // Allocate memory for the bitset structure itself
+    //
+    bitset  = new Bitset<ImplTraits>(numElements);
+	memcpy(bitset->get_blist().get_bits(), m_bits, numElements * sizeof(ANTLR_BITWORD));
+
+    // All seems good
+    //
+    return  bitset;
+}
+
+template <class ImplTraits>
+Bitset<ImplTraits>::Bitset( ANTLR_UINT32 numBits )
+{
+	// Avoid memory thrashing at the up front expense of a few bytes
+	if	(numBits < (8 * ANTLR_BITSET_BITS))
+		numBits = 8 * ANTLR_BITSET_BITS;
+
+	// No we need to allocate the memory for the number of bits asked for
+	// in multiples of ANTLR3_UINT64. 
+	//
+	ANTLR_UINT32 numelements	= ((numBits -1) >> ANTLR_BITSET_LOG_BITS) + 1;
+
+	m_blist.set_bits( (ANTLR_BITWORD*) AllocPolicyType::alloc0(numelements * sizeof(ANTLR_BITWORD)));
+
+	m_blist.set_length( numelements );
+}
+
+template <class ImplTraits>
+Bitset<ImplTraits>::Bitset( const Bitset& bitset )
+	:m_blist(bitset.m_blist)
+{
+}
+
+template <class ImplTraits>
+ANTLR_INLINE Bitset<ImplTraits>*  Bitset<ImplTraits>::clone() const
+{
+	Bitset*  bitset;
+
+    // Allocate memory for the bitset structure itself
+    //
+    bitset  = new Bitset( ANTLR_BITSET_BITS * m_blist.get_length() );
+
+    // Install the actual bits in the source set
+    //
+    memcpy(bitset->m_blist.get_bits(), m_blist.get_bits(), 
+				m_blist.get_length() * sizeof(ANTLR_BITWORD) );
+
+    // All seems good
+    //
+    return  bitset;
+}
+
+template <class ImplTraits>
+Bitset<ImplTraits>*  Bitset<ImplTraits>::bor(Bitset* bitset2)
+{
+	Bitset*  bitset;
+
+    if	(this == NULL)
+		return bitset2->clone();
+
+    if	(bitset2 == NULL)
+		return	this->clone();
+
+    // Allocate memory for the newly ordered bitset structure itself.
+    //
+    bitset  = this->clone();
+    bitset->bitsetORInPlace(bitset2);
+    return  bitset;
+}
+
+template <class ImplTraits>
+void	 Bitset<ImplTraits>::borInPlace(Bitset* bitset2)
+{
+	ANTLR_UINT32   minimum;
+
+    if	(bitset2 == NULL)
+		return;
+
+	// First make sure that the target bitset is big enough
+    // for the new bits to be ored in.
+    //
+    if	( m_blist.get_length() < bitset2->m_blist.get_length() )
+		this->growToInclude( bitset2->m_blist.get_length() * sizeof(ANTLR_BITWORD) );
+    
+    // Or the miniimum number of bits after any resizing went on
+    //
+    if	( m_blist.get_length() < bitset2->m_blist.get_length() )
+		minimum = m_blist.get_length();
+	else
+		minimum = bitset2->m_blist.get_length();
+
+	ANTLR_BITWORD* bits1 = m_blist.get_bits();
+	ANTLR_BITWORD* bits2 = bitset2->m_blist.get_bits();
+	for	(ANTLR_UINT32 i = minimum; i > 0; i--)
+		bits1[i-1] |= bits2[i-1];
+}
+
+template <class ImplTraits>
+ANTLR_UINT32 Bitset<ImplTraits>::size() const
+{
+    ANTLR_UINT32   degree;
+    ANTLR_INT32   i;
+    ANTLR_INT8    bit;
+    
+    // TODO: Come back to this, it may be faster to & with 0x01
+    // then shift right a copy of the 4 bits, than shift left a constant of 1.
+    // But then again, the optimizer might just work this out
+    // anyway.
+    //
+    degree  = 0;
+	ANTLR_BITWORD* bits = m_blist.get_bits();
+    for	(i = m_blist.get_length() - 1; i>= 0; i--)
+    {
+		if  (bits[i] != 0)
+		{
+			for(bit = ANTLR_BITSET_BITS - 1; bit >= 0; bit--)
+			{
+				if((bits[i] & (((ANTLR_BITWORD)1) << bit)) != 0)
+				{
+					degree++;
+				}
+			}
+		}
+    }
+    return degree;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE void	Bitset<ImplTraits>::add(ANTLR_INT32 bit)
+{
+	ANTLR_UINT32   word = Bitset::WordNumber(bit);
+
+    if	(word	>= m_blist.get_length() )
+		this->growToInclude(bit);
+ 
+	ANTLR_BITWORD* bits = m_blist.get_bits();
+	bits[word] |= Bitset::BitMask(bit);
+}
+
+template <class ImplTraits>
+void	Bitset<ImplTraits>::grow(ANTLR_INT32 newSize)
+{
+	ANTLR_BITWORD*   newBits;
+
+    // Space for newly sized bitset - TODO: come back to this and use realloc?, it may
+    // be more efficient...
+    //
+    newBits =  (ANTLR_BITWORD*) AllocPolicyType::alloc0(newSize * sizeof(ANTLR_BITWORD) );
+    if	( m_blist.get_bits() != NULL)
+    {
+		// Copy existing bits
+		//
+		memcpy( newBits, m_blist.get_bits(), m_blist.get_length() * sizeof(ANTLR_BITWORD) );
+
+		// Out with the old bits... de de de derrr
+		//
+		AllocPolicyType::free( m_blist.get_bits() );
+    }
+
+    // In with the new bits... keerrrang.
+    //
+    m_blist.set_bits(newBits);
+    m_blist.set_length(newSize);
+}
+
+template <class ImplTraits>
+bool	Bitset<ImplTraits>::equals(Bitset* bitset2) const
+{
+    ANTLR_UINT32   minimum;
+    ANTLR_UINT32   i;
+
+    if	(this == NULL || bitset2 == NULL)
+		return	false;
+
+    // Work out the minimum comparison set
+    //
+    if	( m_blist.get_length() < bitset2->m_blist.get_length() )
+		minimum = m_blist.get_length();
+    else
+		minimum = bitset2->m_blist.get_length();
+
+    // Make sure explict in common bits are equal
+    //
+    for	(i = minimum - 1; i < minimum ; i--)
+    {
+		ANTLR_BITWORD* bits1 = m_blist.get_bits();
+		ANTLR_BITWORD* bits2 = bitset2->m_blist.get_bits();
+		if  ( bits1[i] != bits2[i])
+			return false;
+    }
+
+    // Now make sure the bits of the larger set are all turned
+    // off.
+    //
+    if	( m_blist.get_length() > minimum)
+    {
+		for (i = minimum ; i < m_blist.get_length(); i++)
+		{
+			ANTLR_BITWORD* bits = m_blist.get_bits();
+			if(bits[i] != 0)
+				return false;
+		}
+    }
+    else if (bitset2->m_blist.get_length() > minimum)
+    {
+		ANTLR_BITWORD* bits = m_blist.get_bits();
+		for (i = minimum; i < bitset2->m_blist.get_length(); i++)
+		{
+			if	( bits[i] != 0 )
+				return	false;
+		}
+    }
+
+    return  true;
+}
+
+template <class ImplTraits>
+bool	Bitset<ImplTraits>::isMember(ANTLR_UINT32 bit) const
+{
+    ANTLR_UINT32    wordNo = Bitset::WordNumber(bit);
+
+    if	(wordNo >= m_blist.get_length())
+		return false;
+    
+	ANTLR_BITWORD* bits = m_blist.get_bits();
+    if	( (bits[wordNo] & Bitset::BitMask(bit)) == 0)
+		return false;
+    else
+		return true;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32 Bitset<ImplTraits>::numBits() const
+{
+	return  m_blist.get_length() << ANTLR_BITSET_LOG_BITS;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE typename ImplTraits::BitsetListType& Bitset<ImplTraits>::get_blist()
+{
+	return m_blist;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE void Bitset<ImplTraits>::remove(ANTLR_UINT32 bit)
+{
+    ANTLR_UINT32    wordNo = Bitset::WordNumber(bit);
+
+    if	(wordNo < m_blist.get_length())
+	{
+		ANTLR_BITWORD* bits = m_blist.get_bits();
+		bits[wordNo] &= ~(Bitset::BitMask(bit));
+	}
+}
+
+template <class ImplTraits>
+ANTLR_INLINE bool Bitset<ImplTraits>::isNilNode() const
+{
+	ANTLR_UINT32    i;
+	ANTLR_BITWORD* bits = m_blist.get_bits();
+	for	(i = m_blist.get_length() -1 ; i < m_blist.get_length(); i--)
+	{
+		if(bits[i] != 0)
+			return false;
+	}
+	return  true;
+}
+
+template <class ImplTraits>
+ANTLR_INT32* Bitset<ImplTraits>::toIntList() const
+{
+	ANTLR_UINT32   numInts;	    // How many integers we will need
+    ANTLR_UINT32   numBits;	    // How many bits are in the set
+    ANTLR_UINT32   i;
+    ANTLR_UINT32   index;
+
+    ANTLR_INT32*  intList;
+
+    numInts = this->size() + 1;
+    numBits = this->numBits();
+ 
+    intList = (ANTLR_INT32*) AllocPolicyType::alloc(numInts * sizeof(ANTLR_INT32));
+    
+    intList[0] = numInts;
+
+    // Enumerate the bits that are turned on
+    //
+    for	(i = 0, index = 1; i<numBits; i++)
+    {
+		if  (this->isMember(i) == true)
+			intList[index++]    = i;
+    }
+
+    // Result set
+    //
+    return  intList;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE Bitset<ImplTraits>::~Bitset()
+{
+	if	(m_blist.get_bits() != NULL)
+		AllocPolicyType::free(m_blist.get_bits());
+    return;
+}
+
+template <class ImplTraits>
+void	Bitset<ImplTraits>::growToInclude(ANTLR_INT32 bit)
+{
+	ANTLR_UINT32	bl;
+	ANTLR_UINT32	nw;
+
+	bl = (m_blist.get_length() << 1);
+	nw = Bitset::NumWordsToHold(bit);
+
+	if	(bl > nw)
+		this->grow(bl);
+	else
+		this->grow(nw);
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_UINT64	Bitset<ImplTraits>::BitMask(ANTLR_UINT32 bitNumber)
+{
+	return  ((ANTLR_UINT64)1) << (bitNumber & (ANTLR_BITSET_MOD_MASK));
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32	Bitset<ImplTraits>::NumWordsToHold(ANTLR_UINT32 bit)
+{
+	return  (bit >> ANTLR_BITSET_LOG_BITS) + 1;
+}
+
+template <class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32	Bitset<ImplTraits>::WordNumber(ANTLR_UINT32 bit)
+{
+	return  bit >> ANTLR_BITSET_LOG_BITS;
+}
+
+template <class ImplTraits>
+void Bitset<ImplTraits>::bitsetORInPlace(Bitset* bitset2)
+{
+	ANTLR_UINT32   minimum;
+    ANTLR_UINT32   i;
+
+    if	(bitset2 == NULL)
+		return;
+
+    // First make sure that the target bitset is big enough
+    // for the new bits to be ored in.
+    //
+    if	( m_blist.get_length() < bitset2->m_blist.get_length() )
+		this->growToInclude( bitset2->m_blist.get_length() * sizeof(ANTLR_BITWORD) );
+    
+    // Or the miniimum number of bits after any resizing went on
+    //
+    if	( m_blist.get_length() < bitset2->m_blist.get_length() )
+		minimum = m_blist.get_length();
+	else
+		minimum = bitset2->m_blist.get_length();
+
+	ANTLR_BITWORD* bits1 = m_blist.get_bits();
+	ANTLR_BITWORD* bits2 = bitset2->m_blist.get_bits();
+    for	(i = minimum; i > 0; i--)
+		bits1[i-1] |= bits2[i-1];
+}
+
+template <class ImplTraits>
+Bitset<ImplTraits>* Bitset<ImplTraits>::BitsetOf(ANTLR_INT32 bit)
+{
+	// Allocate memory for the bitset structure itself
+    // the input parameter is the bit number (0 based)
+    // to include in the bitset, so we need at at least
+    // bit + 1 bits. If any arguments indicate a 
+    // a bit higher than the default number of bits (0 menas default size)
+    // then Add() will take care
+    // of it.
+    //
+	Bitset<ImplTraits>* bitset = new Bitset<ImplTraits>(0);
+	bitset->add(bit);
+	return bitset;
+}
+
+template <class ImplTraits>
+Bitset<ImplTraits>* Bitset<ImplTraits>::BitsetOf(ANTLR_INT32 bit1, ANTLR_INT32 bit2)
+{
+	Bitset<ImplTraits>* bitset = Bitset<ImplTraits>::BitsetOf(bit1);
+	bitset->add(bit2);
+	return bitset;
+}
+
+//static 
+template <class ImplTraits>
+Bitset<ImplTraits>* Bitset<ImplTraits>::BitsetFromList(const IntListType& list)
+{
+	// We have no idea what exactly is in the list
+    // so create a default bitset and then just add stuff
+    // as we enumerate.
+    //
+    Bitset<ImplTraits>* bitset  = new Bitset<ImplTraits>(0);
+	for( int i = 0; i < list.size(); ++i )
+		bitset->add( list[i] );
+
+	return bitset;
+}
+
+ANTLR_END_NAMESPACE()
diff --git a/runtime/Cpp/include/antlr3collections.hpp b/runtime/Cpp/include/antlr3collections.hpp
new file mode 100755
index 0000000..2111403
--- /dev/null
+++ b/runtime/Cpp/include/antlr3collections.hpp
@@ -0,0 +1,285 @@
+#ifndef	ANTLR3COLLECTIONS_HPP
+#define	ANTLR3COLLECTIONS_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    "antlr3defs.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+/* -------------- TRIE Interfaces ---------------- */
+
+/** Structure that holds the payload entry in an ANTLR3_INT_TRIE or ANTLR3_STRING_TRIE
+ */
+template< class ImplTraits, class DataType >
+class TrieEntry : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::AllocPolicyType AllocPolicy;
+
+private:
+	DataType			m_data;
+	TrieEntry*			m_next;	    /* Allows duplicate entries for same key in insertion order	*/
+
+public:
+	TrieEntry(const DataType& data, TrieEntry* next);
+	DataType& get_data();
+	const DataType& get_data() const;
+	TrieEntry* get_next() const;
+	void set_next( TrieEntry* next );
+};
+
+/** Structure that defines an element/node in an ANTLR_INT_TRIE
+ */
+template< class ImplTraits, class DataType >
+class IntTrieNode : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef TrieEntry<ImplTraits, DataType> TrieEntryType;
+	typedef TrieEntryType BucketsType;
+	
+private:
+    ANTLR_UINT32	m_bitNum;	/**< This is the left/right bit index for traversal along the nodes				*/
+    ANTLR_INTKEY	m_key;		/**< This is the actual key that the entry represents if it is a terminal node  */
+    BucketsType*	m_buckets;	/**< This is the data bucket(s) that the key indexes, which may be NULL			*/
+    IntTrieNode*	m_leftN;	/**< Pointer to the left node from here when sKey & bitNum = 0					*/
+    IntTrieNode*	m_rightN;	/**< Pointer to the right node from here when sKey & bitNum, = 1				*/
+
+public:
+	IntTrieNode();
+	~IntTrieNode();
+
+	ANTLR_UINT32 get_bitNum() const;
+	ANTLR_INTKEY get_key() const;
+	BucketsType* get_buckets() const;
+	IntTrieNode* get_leftN() const;
+	IntTrieNode* get_rightN() const;
+	void  set_bitNum( ANTLR_UINT32 bitNum );
+	void  set_key( ANTLR_INTKEY key );
+	void  set_buckets( BucketsType* buckets );
+	void  set_leftN( IntTrieNode* leftN );
+	void  set_rightN( IntTrieNode* rightN );
+};
+  
+/** Structure that defines an ANTLR3_INT_TRIE. For this particular implementation,
+ *  as you might expect, the key is turned into a "string" by looking at bit(key, depth)
+ *  of the integer key. Using 64 bit keys gives us a depth limit of 64 (or bit 0..63)
+ *  and potentially a huge trie. This is the algorithm for a Patricia Trie.
+ *  Note also that this trie [can] accept multiple entries for the same key and is
+ *  therefore a kind of elastic bucket patricia trie.
+ *
+ *  If you find this code useful, please feel free to 'steal' it for any purpose
+ *  as covered by the BSD license under which ANTLR is issued. You can cut the code
+ *  but as the ANTLR library is only about 50K (Windows Vista), you might find it 
+ *  easier to just link the library. Please keep all comments and licenses and so on
+ *  in any version of this you create of course.
+ *
+ *  Jim Idle.
+ *  
+ */
+class IntTrieBase
+{
+public:
+	static const ANTLR_UINT8* get_bitIndex();
+	static const ANTLR_UINT64* get_bitMask();
+};
+ 
+template< class ImplTraits, class DataType >
+class IntTrie : public ImplTraits::AllocPolicyType, public IntTrieBase
+{
+public:
+	typedef TrieEntry<ImplTraits, DataType> TrieEntryType;
+	typedef IntTrieNode<ImplTraits, DataType> IntTrieNodeType;
+	
+private:
+    IntTrieNodeType*	m_root;			/* Root node of this integer trie					*/
+    IntTrieNodeType*	m_current;		/* Used to traverse the TRIE with the next() method	*/
+    ANTLR_UINT32	m_count;			/* Current entry count								*/
+    bool			m_allowDups;		/* Whether this trie accepts duplicate keys			*/
+
+public:
+	/* INT TRIE Implementation of depth 64 bits, being the number of bits
+	 * in a 64 bit integer. 
+	 */
+    IntTrie( ANTLR_UINT32 depth );
+
+	/** Search the int Trie and return a pointer to the first bucket indexed
+	 *  by the key if it is contained in the trie, otherwise NULL.
+	 */
+    TrieEntryType*	get( ANTLR_INTKEY key);
+    bool		del( ANTLR_INTKEY key);
+
+	/** Add an entry into the INT trie.
+	 *  Basically we descend the trie as we do when searching it, which will
+	 *  locate the only node in the trie that can be reached by the bit pattern of the
+	 *  key. If the key is actually at that node, then if the trie accepts duplicates
+	 *  we add the supplied data in a new chained bucket to that data node. If it does
+	 *  not accept duplicates then we merely return FALSE in case the caller wants to know
+	 *  whether the key was already in the trie.
+	 *  If the node we locate is not the key we are looking to add, then we insert a new node
+	 *  into the trie with a bit index of the leftmost differing bit and the left or right 
+	 *  node pointing to itself or the data node we are inserting 'before'. 
+	 */
+    bool		add( ANTLR_INTKEY key, const DataType& data );
+    ~IntTrie();
+};
+
+/**
+ * A topological sort system that given a set of dependencies of a node m on node n,
+ * can sort them in dependency order. This is a generally useful utility object
+ * that does not care what the things are it is sorting. Generally the set
+ * to be sorted will be numeric indexes into some other structure such as an ANTLR3_VECTOR.
+ * I have provided a sort method that given ANTLR3_VECTOR as an input will sort
+ * the vector entries in place, as well as a sort method that just returns an
+ * array of the sorted noded indexes, in case you are not sorting ANTLR3_VECTORS but
+ * some set of your own device.
+ *
+ * Of the two main algorithms that could be used, I chose to use the depth first
+ * search for unvisited nodes as a) This runs in linear time, and b) it is what
+ * we used in the ANTLR Tool to perform a topological sort of the input grammar files
+ * based on their dependencies.
+ */
+template<class ImplTraits>
+class Topo : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::BitsetType BitsetType;
+	typedef typename ImplTraits::AllocPolicyType AllocPolicyType;
+
+private:
+    /**
+     * A vector of vectors of edges, built by calling the addEdge method()
+     * to indicate that node number n depends on node number m. Each entry in the vector
+     * contains a bitset, which has a bit index set for each node upon which the
+     * entry node depends.
+     */
+    BitsetType**	m_edges;
+
+    /**
+     * A vector used to build up the sorted output order. Note that
+     * as the vector contains UINT32 then the maximum node index is
+     * 'limited' to 2^32, as nodes should be zero based.
+     */
+    ANTLR_UINT32*				m_sorted;
+
+    /**
+     * A vector used to detect cycles in the edge dependecies. It is used
+     * as a stack and each time we descend a node to one of its edges we
+     * add the node into this stack. If we find a node that we have already
+     * visited in the stack, then it means there wasa cycle such as 9->8->1->9
+     * as the only way a node can be on the stack is if we are currently
+     * descnding from it as we remove it from the stack as we exit from
+     * descending its dependencies
+     */
+    ANTLR_UINT32*		m_cycle;
+
+    /**
+     * A flag that indicates the algorithm found a cycle in the edges
+     * such as 9->8->1->9
+     * If this flag is set after you have called one of the sort routines
+     * then the detected cycle will be contained in the cycle array and
+     * cycleLimit will point to the one after the last entry in the cycle.
+     */
+    bool				m_hasCycle;
+
+    /**
+     * A watermark used to accumulate potential cycles in the cycle array.
+     * This should be zero when we are done. Check hasCycle after calling one
+     * of the sort methods and if it is true then you can find the cycle
+     * in cycle[0]...cycle[cycleMark-1]
+     */
+    ANTLR_UINT32		m_cycleMark;
+    
+    /**
+     * One more than the largest node index that is contained in edges/sorted.
+     */
+    ANTLR_UINT32		m_limit;
+
+    /**
+     * The set of visited nodes as determined by a set entry in
+     * the bitmap.
+     */
+    BitsetType*			m_visited;
+
+public:
+	Topo();
+    /**
+     * A method that adds an edge from one node to another. An edge
+     * of n -> m indicates that node n is dependent on node m. Note that
+     * while building these edges, it is perfectly OK to add nodes out of
+     * sequence. So, if you have edges:
+     *
+     * 3 -> 0
+     * 2 -> 1
+     * 1 -> 3
+     *
+     * The you can add them in that order and so add node 3 before nodes 2 and 1
+     *
+     */
+    void  addEdge(ANTLR_UINT32 edge, ANTLR_UINT32 dependency);
+
+
+    /**
+     * A method that returns a pointer to an array of sorted node indexes.
+     * The array is sorted in topological sorted order. Note that the array
+     * is only as large as the largest node index you created an edge for. This means
+     * that if you had an input of 32 nodes, but that largest node with an edge
+     * was 16, then the returned array will be the sorted order of the first 16
+     * nodes and the last 16 nodes of your array are basically fine as they are
+     * as they had no dependencies and do not need any particular sort order.
+     *
+     * NB: If the structure that contains the array is freed, then the sorted
+     * array will be freed too so you should use the value of limit to
+     * make a long term copy of this array if you do not want to keep the topo
+     * structure around as well.
+     */
+    ANTLR_UINT32*  sortToArray();
+
+    /** 
+     * A method that sorts the supplied ANTLR3_VECTOR in place based
+     * on the previously supplied edge data.
+     */
+	template<typename DataType>
+    void   sortVector( typename ImplTraits::template VectorType<DataType>& v);
+
+	void   DFS(ANTLR_UINT32 node);
+
+    /**
+     *  A method to free this structure and any associated memory.
+     */
+	~Topo();
+};
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3collections.inl"
+    
+#endif
+
+
diff --git a/runtime/Cpp/include/antlr3collections.inl b/runtime/Cpp/include/antlr3collections.inl
new file mode 100755
index 0000000..fb713c2
--- /dev/null
+++ b/runtime/Cpp/include/antlr3collections.inl
@@ -0,0 +1,995 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template< class ImplTraits, class DataType >
+ANTLR_INLINE TrieEntry<ImplTraits, DataType>::TrieEntry(const DataType& data, TrieEntry* next)
+	:m_data(data)
+{
+	m_next = next;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE DataType& TrieEntry<ImplTraits, DataType>::get_data()
+{
+	return m_data;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE const DataType& TrieEntry<ImplTraits, DataType>::get_data() const
+{
+	return m_data;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE TrieEntry<ImplTraits, DataType>* TrieEntry<ImplTraits, DataType>::get_next() const
+{
+	return m_next;
+}
+
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void TrieEntry<ImplTraits, DataType>::set_next( TrieEntry* next )
+{
+	m_next = next;
+}
+
+template< class ImplTraits, class DataType >
+ANTLR_INLINE ANTLR_UINT32 IntTrieNode<ImplTraits, DataType>::get_bitNum() const
+{
+	return m_bitNum;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE ANTLR_INTKEY IntTrieNode<ImplTraits, DataType>::get_key() const
+{
+	return m_key;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE typename IntTrieNode<ImplTraits, DataType>::BucketsType* IntTrieNode<ImplTraits, DataType>::get_buckets() const
+{
+	return m_buckets;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE IntTrieNode<ImplTraits, DataType>* IntTrieNode<ImplTraits, DataType>::get_leftN() const
+{
+	return m_leftN;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE IntTrieNode<ImplTraits, DataType>* IntTrieNode<ImplTraits, DataType>::get_rightN() const
+{
+	return m_rightN;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void IntTrieNode<ImplTraits, DataType>::set_bitNum( ANTLR_UINT32 bitNum )
+{
+	m_bitNum = bitNum;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void IntTrieNode<ImplTraits, DataType>::set_key( ANTLR_INTKEY key )
+{
+	m_key = key;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void IntTrieNode<ImplTraits, DataType>::set_buckets( BucketsType* buckets )
+{
+	m_buckets = buckets;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void IntTrieNode<ImplTraits, DataType>::set_leftN( IntTrieNode* leftN )
+{
+	m_leftN = leftN;
+}
+template< class ImplTraits, class DataType >
+ANTLR_INLINE void IntTrieNode<ImplTraits, DataType>::set_rightN( IntTrieNode* rightN )
+{
+	m_rightN = rightN;
+}
+
+ANTLR_INLINE const ANTLR_UINT8* IntTrieBase::get_bitIndex()
+{
+	static ANTLR_UINT8 bitIndex[256] = 
+	{ 
+		0,													// 0 - Just for padding
+		0,													// 1
+		1, 1,												// 2..3
+		2, 2, 2, 2,											// 4..7
+		3, 3, 3, 3, 3, 3, 3, 3,								// 8+
+		4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,	    // 16+
+		5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,	    // 32+
+		5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,	    
+		6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,	    // 64+
+		6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+		6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+		6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,	    // 128+
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+		7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
+	};
+	return bitIndex;
+}
+
+ANTLR_INLINE const ANTLR_UINT64* IntTrieBase::get_bitMask()
+{
+	static ANTLR_UINT64 bitMask[64] = 
+	{
+		0x0000000000000001ULL, 0x0000000000000002ULL, 0x0000000000000004ULL, 0x0000000000000008ULL,
+		0x0000000000000010ULL, 0x0000000000000020ULL, 0x0000000000000040ULL, 0x0000000000000080ULL,
+		0x0000000000000100ULL, 0x0000000000000200ULL, 0x0000000000000400ULL, 0x0000000000000800ULL,
+		0x0000000000001000ULL, 0x0000000000002000ULL, 0x0000000000004000ULL, 0x0000000000008000ULL,
+		0x0000000000010000ULL, 0x0000000000020000ULL, 0x0000000000040000ULL, 0x0000000000080000ULL,
+		0x0000000000100000ULL, 0x0000000000200000ULL, 0x0000000000400000ULL, 0x0000000000800000ULL,
+		0x0000000001000000ULL, 0x0000000002000000ULL, 0x0000000004000000ULL, 0x0000000008000000ULL,
+		0x0000000010000000ULL, 0x0000000020000000ULL, 0x0000000040000000ULL, 0x0000000080000000ULL,
+		0x0000000100000000ULL, 0x0000000200000000ULL, 0x0000000400000000ULL, 0x0000000800000000ULL,
+		0x0000001000000000ULL, 0x0000002000000000ULL, 0x0000004000000000ULL, 0x0000008000000000ULL,
+		0x0000010000000000ULL, 0x0000020000000000ULL, 0x0000040000000000ULL, 0x0000080000000000ULL,
+		0x0000100000000000ULL, 0x0000200000000000ULL, 0x0000400000000000ULL, 0x0000800000000000ULL,
+		0x0001000000000000ULL, 0x0002000000000000ULL, 0x0004000000000000ULL, 0x0008000000000000ULL,
+		0x0010000000000000ULL, 0x0020000000000000ULL, 0x0040000000000000ULL, 0x0080000000000000ULL,
+		0x0100000000000000ULL, 0x0200000000000000ULL, 0x0400000000000000ULL, 0x0800000000000000ULL,
+		0x1000000000000000ULL, 0x2000000000000000ULL, 0x4000000000000000ULL, 0x8000000000000000ULL
+	};
+
+	return bitMask;
+}
+
+template< class ImplTraits, class DataType >
+IntTrie<ImplTraits, DataType>::IntTrie( ANTLR_UINT32 depth )
+{
+	/* Now we need to allocate the root node. This makes it easier
+	 * to use the tree as we don't have to do anything special 
+	 * for the root node.
+	 */
+	m_root	= new IntTrieNodeType;
+
+	/* Now we seed the root node with the index being the
+	 * highest left most bit we want to test, which limits the
+	 * keys in the trie. This is the trie 'depth'. The limit for
+	 * this implementation is 63 (bits 0..63).
+	 */
+	m_root->set_bitNum( depth );
+
+	/* And as we have nothing in here yet, we set both child pointers
+	 * of the root node to point back to itself.
+	 */
+	m_root->set_leftN( m_root );
+	m_root->set_rightN( m_root );
+	m_count			= 0;
+
+	/* Finally, note that the key for this root node is 0 because
+	 * we use calloc() to initialise it.
+	 */
+	m_allowDups = false;
+	m_current   = NULL;
+}
+
+template< class ImplTraits, class DataType >
+IntTrie<ImplTraits, DataType>::~IntTrie()
+{
+    /* Descend from the root and free all the nodes
+     */
+    delete m_root;
+
+    /* the nodes are all gone now, so we need only free the memory
+     * for the structure itself
+     */
+}
+
+template< class ImplTraits, class DataType >
+typename IntTrie<ImplTraits, DataType>::TrieEntryType*	IntTrie<ImplTraits, DataType>::get( ANTLR_INTKEY key)
+{
+	IntTrieNodeType*    thisNode; 
+	IntTrieNodeType*    nextNode; 
+
+	if (m_count == 0)
+		return NULL;	    /* Nothing in this trie yet	*/
+
+	/* Starting at the root node in the trie, compare the bit index
+	 * of the current node with its next child node (starts left from root).
+	 * When the bit index of the child node is greater than the bit index of the current node
+	 * then by definition (as the bit index decreases as we descent the trie)
+	 * we have reached a 'backward' pointer. A backward pointer means we
+	 * have reached the only node that can be reached by the bits given us so far
+	 * and it must either be the key we are looking for, or if not then it
+	 * means the entry was not in the trie, and we return NULL. A backward pointer
+	 * points back in to the tree structure rather than down (deeper) within the
+	 * tree branches.
+	 */
+	thisNode	= m_root;		/* Start at the root node		*/
+	nextNode	= thisNode->get_leftN();	/* Examine the left node from the root	*/
+
+	/* While we are descending the tree nodes...
+	 */
+	const ANTLR_UINT64* bitMask = this->get_bitMask();
+	while( thisNode->get_bitNum() > nextNode->get_bitNum() )
+	{
+		/* Next node now becomes the new 'current' node
+		 */
+		thisNode    = nextNode;
+
+		/* We now test the bit indicated by the bitmap in the next node
+		 * in the key we are searching for. The new next node is the
+		 * right node if that bit is set and the left node it is not.
+		 */
+		if (key & bitMask[nextNode->get_bitNum()])
+		{
+			nextNode = nextNode->get_rightN();	/* 1 is right	*/
+		}
+		else
+		{
+			nextNode = nextNode->get_leftN();		/* 0 is left	*/
+		}
+	}
+
+	/* Here we have reached a node where the bitMap index is lower than
+	 * its parent. This means it is pointing backward in the tree and
+	 * must therefore be a terminal node, being the only point than can
+	 * be reached with the bits seen so far. It is either the actual key
+	 * we wanted, or if that key is not in the trie it is another key
+	 * that is currently the only one that can be reached by those bits.
+	 * That situation would obviously change if the key was to be added
+	 * to the trie.
+	 *
+	 * Hence it only remains to test whether this is actually the key or not.
+	 */
+	if (nextNode->get_key() == key)
+	{
+		/* This was the key, so return the entry pointer
+		 */
+		return	nextNode->get_buckets();
+	}
+	else
+	{
+		return	NULL;	/* That key is not in the trie (note that we set the pointer to -1 if no payload) */
+	}
+}
+
+template< class ImplTraits, class DataType >
+bool	IntTrie<ImplTraits, DataType>::del( ANTLR_INTKEY key)
+{
+    IntTrieNodeType*   p;
+
+    p = m_root;
+    
+    return false;
+
+}
+
+template< class ImplTraits, class DataType >
+bool	IntTrie<ImplTraits, DataType>::add( ANTLR_INTKEY key, const DataType& data  )
+{
+	IntTrieNodeType*   thisNode;
+	IntTrieNodeType*   nextNode;
+	IntTrieNodeType*   entNode;
+	ANTLR_UINT32	depth;
+	TrieEntryType*	    newEnt;
+	TrieEntryType*	    nextEnt;
+	ANTLR_INTKEY		    xorKey;
+
+	/* Cache the bit depth of this trie, which is always the highest index, 
+	 * which is in the root node
+	 */
+	depth   = m_root->get_bitNum();
+
+	thisNode	= m_root;		/* Start with the root node	    */
+	nextNode	= m_root->get_leftN();	/* And assume we start to the left  */
+
+	/* Now find the only node that can be currently reached by the bits in the
+	 * key we are being asked to insert.
+	 */
+	const ANTLR_UINT64* bitMask = this->get_bitMask();
+	while (thisNode->get_bitNum()  > nextNode->get_bitNum() )
+	{
+		/* Still descending the structure, next node becomes current.
+		 */
+		thisNode = nextNode;
+
+		if (key & bitMask[nextNode->get_bitNum()])
+		{
+			/* Bit at the required index was 1, so travers the right node from here
+			 */
+			nextNode = nextNode->get_rightN();
+		}
+		else
+		{
+			/* Bit at the required index was 0, so we traverse to the left
+			 */
+			nextNode = nextNode->get_leftN();
+		}
+	}
+	/* Here we have located the only node that can be reached by the
+	 * bits in the requested key. It could in fact be that key or the node
+	 * we need to use to insert the new key.
+	 */
+	if (nextNode->get_key() == key)
+	{
+		/* We have located an exact match, but we will only append to the bucket chain
+		 * if this trie accepts duplicate keys.
+		 */
+		if (m_allowDups ==true)
+		{
+			/* Yes, we are accepting duplicates
+			 */
+			newEnt = new TrieEntryType(data, NULL);
+
+			/* We want to be able to traverse the stored elements in the order that they were
+			 * added as duplicate keys. We might need to revise this opinion if we end up having many duplicate keys
+			 * as perhaps reverse order is just as good, so long as it is ordered.
+			 */
+			nextEnt = nextNode->get_buckets();
+			while (nextEnt->get_next() != NULL)
+			{
+				nextEnt = nextEnt->get_next();    
+			}
+			nextEnt->set_next(newEnt);
+
+			m_count++;
+			return  true;
+		}
+		else
+		{
+			/* We found the key is already there and we are not allowed duplicates in this
+			 * trie.
+			 */
+			return  false;
+		}
+	}
+
+	/* Here we have discovered the only node that can be reached by the bits in the key
+	 * but we have found that this node is not the key we need to insert. We must find the
+	 * the leftmost bit by which the current key for that node and the new key we are going 
+	 * to insert, differ. While this nested series of ifs may look a bit strange, experimentation
+	 * showed that it allows a machine code path that works well with predicated execution
+	 */
+	xorKey = (key ^ nextNode->get_key() );   /* Gives 1 bits only where they differ then we find the left most 1 bit*/
+
+	/* Most common case is a 32 bit key really
+	 */
+	const ANTLR_UINT8* bitIndex = this->get_bitIndex();
+#ifdef	ANTLR_USE_64BIT
+	if	(xorKey & 0xFFFFFFFF00000000)
+	{
+		if  (xorKey & 0xFFFF000000000000)
+		{
+			if	(xorKey & 0xFF00000000000000)
+			{
+				depth = 56 + bitIndex[((xorKey & 0xFF00000000000000)>>56)];
+			}
+			else
+			{
+				depth = 48 + bitIndex[((xorKey & 0x00FF000000000000)>>48)];
+			}
+		}
+		else
+		{
+			if	(xorKey & 0x0000FF0000000000)
+			{
+				depth = 40 + bitIndex[((xorKey & 0x0000FF0000000000)>>40)];
+			}
+			else
+			{
+				depth = 32 + bitIndex[((xorKey & 0x000000FF00000000)>>32)];
+			}
+		}
+	}
+	else
+#endif
+	{
+		if  (xorKey & 0x00000000FFFF0000)
+		{
+			if	(xorKey & 0x00000000FF000000)
+			{
+				depth = 24 + bitIndex[((xorKey & 0x00000000FF000000)>>24)];
+			}
+			else
+			{
+				depth = 16 + bitIndex[((xorKey & 0x0000000000FF0000)>>16)];
+			}
+		}
+		else
+		{
+			if	(xorKey & 0x000000000000FF00)
+			{
+				depth = 8 + bitIndex[((xorKey & 0x0000000000000FF00)>>8)];
+			}
+			else
+			{
+				depth = bitIndex[xorKey & 0x00000000000000FF];
+			}
+		}
+	}
+
+    /* We have located the leftmost differing bit, indicated by the depth variable. So, we know what
+     * bit index we are to insert the new entry at. There are two cases, being where the two keys
+     * differ at a bit position that is not currently part of the bit testing, where they differ on a bit
+     * that is currently being skipped in the indexed comparisons, and where they differ on a bit
+     * that is merely lower down in the current bit search. If the bit index went bit 4, bit 2 and they differ
+     * at bit 3, then we have the "skipped" bit case. But if that chain was Bit 4, Bit 2 and they differ at bit 1
+     * then we have the easy bit <pun>.
+     *
+     * So, set up to descend the tree again, but this time looking for the insert point
+     * according to whether we skip the bit that differs or not.
+     */
+    thisNode	= m_root;
+    entNode	= m_root->get_leftN();
+
+    /* Note the slight difference in the checks here to cover both cases
+     */
+    while (thisNode->get_bitNum() > entNode->get_bitNum() && entNode->get_bitNum() > depth)
+    {
+		/* Still descending the structure, next node becomes current.
+		 */
+		thisNode = entNode;
+
+		if (key & bitMask[entNode->get_bitNum()])
+		{
+			/* Bit at the required index was 1, so traverse the right node from here
+			 */
+			entNode = entNode->get_rightN();
+		}
+		else
+		{
+			/* Bit at the required index was 0, so we traverse to the left
+			 */
+			entNode = entNode->get_leftN();
+		}
+    }
+
+    /* We have located the correct insert point for this new key, so we need
+     * to allocate our entry and insert it etc.
+     */
+    nextNode	= new IntTrieNodeType();
+
+    /* Build a new entry block for the new node
+     */
+    newEnt = new TrieEntryType(data, NULL);
+
+	/* Install it
+     */
+    nextNode->set_buckets(newEnt);
+    nextNode->set_key(key);
+    nextNode->set_bitNum( depth );
+
+    /* Work out the right and left pointers for this new node, which involve
+     * terminating with the current found node either right or left according
+     * to whether the current index bit is 1 or 0
+     */
+    if (key & bitMask[depth])
+    {
+		nextNode->set_leftN(entNode);	    /* Terminates at previous position	*/
+		nextNode->set_rightN(nextNode);	    /* Terminates with itself		*/
+    }
+    else
+    {
+		nextNode->set_rightN(entNode);	    /* Terminates at previous position	*/
+		nextNode->set_leftN(nextNode);	    /* Terminates with itself		*/		
+    }
+
+    /* Finally, we need to change the pointers at the node we located
+     * for inserting. If the key bit at its index is set then the right
+     * pointer for that node becomes the newly created node, otherwise the left 
+     * pointer does.
+     */
+    if (key & bitMask[thisNode->get_bitNum()] )
+    {
+		thisNode->set_rightN( nextNode );
+    }
+    else
+    {
+		thisNode->set_leftN(nextNode);
+    }
+
+    /* Et voila
+     */
+    m_count++;
+    return  true;
+}
+
+template< class ImplTraits, class DataType >
+IntTrieNode<ImplTraits, DataType>::IntTrieNode()
+{
+	m_bitNum = 0;
+	m_key = 0;
+	m_buckets = NULL;
+	m_leftN = NULL;
+	m_rightN = NULL;
+}
+
+template< class ImplTraits, class DataType >
+IntTrieNode<ImplTraits, DataType>::~IntTrieNode()
+{
+	TrieEntryType*	thisEntry;
+    TrieEntryType*	nextEntry;
+
+    /* If this node has a left pointer that is not a back pointer
+     * then recursively call to free this
+     */
+    if ( m_bitNum > m_leftN->get_bitNum())
+    {
+		/* We have a left node that needs descending, so do it.
+		 */
+		delete m_leftN;
+    }
+
+    /* The left nodes from here should now be dealt with, so 
+     * we need to descend any right nodes that are not back pointers
+     */
+    if ( m_bitNum > m_rightN->get_bitNum() )
+    {
+		/* There are some right nodes to descend and deal with.
+		 */
+		delete m_rightN;
+    }
+
+    /* Now all the children are dealt with, we can destroy
+     * this node too
+     */
+    thisEntry	= m_buckets;
+
+    while (thisEntry != NULL)
+    {
+		nextEntry   = thisEntry->get_next();
+
+		/* Now free the data for this bucket entry
+		 */
+		delete thisEntry;
+		thisEntry = nextEntry;	    /* See if there are any more to free    */
+    }
+
+    /* The bucket entry is now gone, so we can free the memory for
+     * the entry itself.
+     */
+
+    /* And that should be it for everything under this node and itself
+     */
+}
+
+/**
+ * Allocate and initialize a new ANTLR3 topological sorter, which can be
+ * used to define edges that identify numerical node indexes that depend on other
+ * numerical node indexes, which can then be sorted topologically such that
+ * any node is sorted after all its dependent nodes.
+ *
+ * Use:
+ *
+ * /verbatim
+
+  pANTLR3_TOPO topo;
+  topo = antlr3NewTopo();
+
+  if (topo == NULL) { out of memory }
+
+  topo->addEdge(topo, 3, 0); // Node 3 depends on node 0
+  topo->addEdge(topo, 0, 1); // Node - depends on node 1
+  topo->sortVector(topo, myVector); // Sort the vector in place (node numbers are the vector entry numbers)
+
+ * /verbatim
+ */
+template<class ImplTraits>
+Topo<ImplTraits>::Topo()
+{
+    // Initialize variables
+    //
+    m_visited   = NULL;                 // Don't know how big it is yet
+    m_limit     = 1;                    // No edges added yet
+    m_edges     = NULL;                 // No edges added yet
+    m_sorted    = NULL;                 // Nothing sorted at the start
+    m_cycle     = NULL;                 // No cycles at the start
+    m_cycleMark = 0;                    // No cycles at the start
+    m_hasCycle  = false;         // No cycle at the start
+}
+
+// Topological sorter
+//
+template<class ImplTraits>
+void Topo<ImplTraits>::addEdge(ANTLR_UINT32 edge, ANTLR_UINT32 dependency)
+{
+	ANTLR_UINT32   i;
+    ANTLR_UINT32   maxEdge;
+    BitsetType*  edgeDeps;
+
+    if (edge>dependency)
+    {
+        maxEdge = edge;
+    }
+    else
+    {
+        maxEdge = dependency;
+    }
+    // We need to add an edge to says that the node indexed by 'edge' is
+    // dependent on the node indexed by 'dependency'
+    //
+
+    // First see if we have enough room in the edges array to add the edge?
+    //
+    if ( m_edges == NULL)
+    {
+        // We don't have any edges yet, so create an array to hold them
+        //
+        m_edges = AllocPolicyType::alloc0(sizeof(BitsetType*) * (maxEdge + 1));
+
+        // Set the limit to what we have now
+        //
+        m_limit = maxEdge + 1;
+    }
+    else if (m_limit <= maxEdge)
+    {
+        // WE have some edges but not enough
+        //
+        m_edges = AllocPolicyType::realloc(m_edges, sizeof(BitsetType*) * (maxEdge + 1));
+
+        // Initialize the new bitmaps to ;indicate we have no edges defined yet
+        //
+        for (i = m_limit; i <= maxEdge; i++)
+        {
+            *((m_edges) + i) = NULL;
+        }
+
+        // Set the limit to what we have now
+        //
+        m_limit = maxEdge + 1;
+    }
+
+    // If the edge was flagged as depending on itself, then we just
+    // do nothing as it means this routine was just called to add it
+    // in to the list of nodes.
+    //
+    if  (edge == dependency)
+    {
+        return;
+    }
+
+    // Pick up the bit map for the requested edge
+    //
+    edgeDeps = *((m_edges) + edge);
+
+    if  (edgeDeps == NULL)
+    {
+        // No edges are defined yet for this node
+        //
+        edgeDeps                = new BitsetType(0);
+        *((m_edges) + edge) = edgeDeps;
+    }
+
+    // Set the bit in the bitmap that corresponds to the requested
+    // dependency.
+    //
+    edgeDeps->add(dependency);
+
+    // And we are all set
+    //
+    return;
+
+}
+
+/**
+ * Given a starting node, descend its dependent nodes (ones that it has edges
+ * to) until we find one without edges. Having found a node without edges, we have
+ * discovered the bottom of a depth first search, which we can then ascend, adding
+ * the nodes in order from the bottom, which gives us the dependency order.
+ */
+template<class ImplTraits>
+void Topo<ImplTraits>::DFS(ANTLR_UINT32 node)
+{
+	BitsetType* edges;
+
+    // Guard against a revisit and check for cycles
+    //
+    if  (m_hasCycle == true)
+    {
+        return; // We don't do anything else if we found a cycle
+    }
+
+    if  ( m_visited->isMember(node))
+    {
+        // Check to see if we found a cycle. To do this we search the
+        // current cycle stack and see if we find this node already in the stack.
+        //
+        ANTLR_UINT32   i;
+
+        for (i=0; i< m_cycleMark; i++)
+        {
+            if  ( m_cycle[i] == node)
+            {
+                // Stop! We found a cycle in the input, so rejig the cycle
+                // stack so that it only contains the cycle and set the cycle flag
+                // which will tell the caller what happened
+                //
+                ANTLR_UINT32 l;
+
+                for (l = i; l < m_cycleMark; l++)
+                {
+                    m_cycle[l - i] = m_cycle[l];    // Move to zero base in the cycle list
+                }
+
+                // Recalculate the limit
+                //
+                m_cycleMark -= i;
+
+                // Signal disaster
+                //
+                m_hasCycle = true;
+            }
+        }
+        return;
+    }
+
+    // So far, no cycles have been found and we have not visited this node yet,
+    // so this node needs to go into the cycle stack before we continue
+    // then we will take it out of the stack once we have descended all its
+    // dependencies.
+    //
+    m_cycle[m_cycleMark++] = node;
+
+    // First flag that we have visited this node
+    //
+    m_visited->add(node);
+
+    // Now, if this node has edges, then we want to ensure we visit
+    // them all before we drop through and add this node into the sorted
+    // list.
+    //
+    edges = *((m_edges) + node);
+    if  (edges != NULL)
+    {
+        // We have some edges, so visit each of the edge nodes
+        // that have not already been visited.
+        //
+        ANTLR_UINT32   numBits;	    // How many bits are in the set
+        ANTLR_UINT32   i;
+        ANTLR_UINT32   range;
+
+        numBits = edges->numBits();
+        range   = edges->size();   // Number of set bits
+
+        // Stop if we exahust the bit list or have checked the
+        // number of edges that this node refers to (so we don't
+        // check bits at the end that cannot possibly be set).
+        //
+        for (i=0; i<= numBits && range > 0; i++)
+        {
+            if  (edges->isMember(i))
+            {
+                range--;        // About to check another one
+
+                // Found an edge, make sure we visit and descend it
+                //
+                this->DFS(i);
+            }
+        }
+    }
+
+    // At this point we will have visited all the dependencies
+    // of this node and they will be ordered (even if there are cycles)
+    // So we just add the node into the sorted list at the
+    // current index position.
+    //
+    m_sorted[m_limit++] = node;
+
+    // Remove this node from the cycle list if we have not detected a cycle
+    //
+    if  (m_hasCycle == false)
+    {
+        m_cycleMark--;
+    }
+
+    return;
+}
+
+template<class ImplTraits>
+ANTLR_UINT32*  Topo<ImplTraits>::sortToArray()
+{
+	ANTLR_UINT32 v;
+    ANTLR_UINT32 oldLimit;
+
+    // Guard against being called with no edges defined
+    //
+    if  (m_edges == NULL)
+    {
+        return 0;
+    }
+    // First we need a vector to populate with enough
+    // entries to accomodate the sorted list and another to accomodate
+    // the maximum cycle we could detect which is all nodes such as 0->1->2->3->0
+    //
+    m_sorted    = AllocPolicyType::alloc( m_limit * sizeof(ANTLR_UINT32) );
+    m_cycle     = AllocPolicyType::alloc( m_limit * sizeof(ANTLR_UINT32));
+
+    // Next we need an empty bitset to show whether we have visited a node
+    // or not. This is the bit that gives us linear time of course as we are essentially
+    // dropping through the nodes in depth first order and when we get to a node that
+    // has no edges, we pop back up the stack adding the nodes we traversed in reverse
+    // order.
+    //
+    m_visited   = new BitsetType(0);
+
+    // Now traverse the nodes as if we were just going left to right, but
+    // then descend each node unless it has already been visited.
+    //
+    oldLimit    = m_limit;     // Number of nodes to traverse linearly
+    m_limit = 0;               // Next entry in the sorted table
+
+    for (v = 0; v < oldLimit; v++)
+    {
+        // If we did not already visit this node, then descend it until we
+        // get a node without edges or arrive at a node we have already visited.
+        //
+        if  (m_visited->isMember(v) == false)
+        {
+            // We have not visited this one so descend it
+            //
+            this->DFS(v);
+        }
+
+        // Break the loop if we detect a cycle as we have no need to go any
+        // further
+        //
+        if  (m_hasCycle == true)
+        {
+            break;
+        }
+    }
+
+    // Reset the limit to the number we recorded as if we hit a
+    // cycle, then limit will have stopped at the node where we
+    // discovered the cycle, but in order to free the edge bitmaps
+    // we need to know how many we may have allocated and traverse them all.
+    //
+    m_limit = oldLimit;
+
+    // Having traversed all the nodes we were given, we
+    // are guaranteed to have ordered all the nodes or detected a
+    // cycle.
+    //
+    return m_sorted;
+}
+
+template<class ImplTraits>
+	template<typename DataType>
+void   Topo<ImplTraits>::sortVector(  typename ImplTraits::template VectorType<DataType>& v )
+{
+    // To sort a vector, we first perform the
+    // sort to an array, then use the results to reorder the vector
+    // we are given. This is just a convenience routine that allows you to
+    // sort the children of a tree node into topological order before or
+    // during an AST walk. This can be useful for optimizations that require
+    // dag reorders and also when the input stream defines thigns that are
+    // interdependent and you want to walk the list of the generated trees
+    // for those things in topological order so you can ignore the interdependencies
+    // at that point.
+    //
+    ANTLR_UINT32 i;
+
+    // Used as a lookup index to find the current location in the vector of
+    // the vector entry that was originally at position [0], [1], [2] etc
+    //
+    ANTLR_UINT32*  vIndex;
+
+    // Sort into an array, then we can use the array that is
+    // stored in the topo
+    //
+    if  (this->sortToArray() == 0)
+    {
+        return;     // There were no edges
+    }
+
+    if  (m_hasCycle == true)
+    {
+        return;  // Do nothing if we detected a cycle
+    }
+
+    // Ensure that the vector we are sorting is at least as big as the
+    // the input sequence we were adsked to sort. It does not matter if it is
+    // bigger as thaat probably just means that nodes numbered higher than the
+    // limit had no dependencies and so can be left alone.
+    //
+    if  (m_limit > v.size() )
+    {
+        // We can only sort the entries that we have dude! The caller is
+        // responsible for ensuring the vector is the correct one and is the
+        // correct size etc.
+        //
+        m_limit = v.size();
+    }
+    // We need to know the locations of each of the entries
+    // in the vector as we don't want to duplicate them in a new vector. We
+    // just use an indirection table to get the vector entry for a particular sequence
+    // acording to where we moved it last. Then we can just swap vector entries until
+    // we are done :-)
+    //
+    vIndex = AllocPolicyType::alloc(m_limit * sizeof(ANTLR_UINT32));
+
+    // Start index, each vector entry is located where you think it is
+    //
+    for (i = 0; i < m_limit; i++)
+    {
+        vIndex[i] = i;
+    }
+
+    // Now we traverse the sorted array and moved the entries of
+    // the vector around according to the sort order and the indirection
+    // table we just created. The index telsl us where in the vector the
+    // original element entry n is now located via vIndex[n].
+    //
+    for (i=0; i < m_limit; i++)
+    {
+        ANTLR_UINT32   ind;
+
+        // If the vector entry at i is already the one that it
+        // should be, then we skip moving it of course.
+        //
+        if  (vIndex[m_sorted[i]] == i)
+        {
+            continue;
+        }
+
+        // The vector entry at i, should be replaced with the
+        // vector entry indicated by topo->sorted[i]. The vector entry
+        // at topo->sorted[i] may have already been swapped out though, so we
+        // find where it is now and move it from there to i.
+        //
+        ind     = vIndex[m_sorted[i]];
+		std::swap( v[i], v[ind] );
+
+        // Update our index. The element at i is now the one we wanted
+        // to be sorted here and the element we swapped out is now the
+        // element that was at i just before we swapped it. If you are lost now
+        // don't worry about it, we are just reindexing on the fly is all.
+        //
+        vIndex[m_sorted[i]] = i;
+        vIndex[i] = ind;
+    }
+
+    // Having traversed all the entries, we have sorted the vector in place.
+    //
+    AllocPolicyType::free(vIndex);
+    return;
+}
+
+template<class ImplTraits>
+Topo<ImplTraits>::~Topo()
+{
+    ANTLR_UINT32   i;
+
+    // Free the result vector
+    //
+    if  (m_sorted != NULL)
+    {
+        AllocPolicyType::free(m_sorted);
+    }
+
+    // Free the visited map
+    //
+    if  (m_visited != NULL)
+    {
+		delete m_visited;
+    }
+
+    // Free any edgemaps
+    //
+    if  (m_edges != NULL)
+    {
+        Bitset<AllocPolicyType>* edgeList;
+
+        for (i=0; i<m_limit; i++)
+        {
+            edgeList = *((m_edges) + i);
+            if  (edgeList != NULL)
+            {
+				delete edgeList;
+            }
+        }
+
+        AllocPolicyType::free( m_edges );
+    }
+    m_edges = NULL;
+    
+    // Free any cycle map
+    //
+    if  (m_cycle != NULL)
+    {
+        AllocPolicyType::free(m_cycle);
+    }
+}
+
+
+ANTLR_END_NAMESPACE()
diff --git a/runtime/Cpp/include/antlr3commontoken.hpp b/runtime/Cpp/include/antlr3commontoken.hpp
new file mode 100755
index 0000000..fd306e7
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontoken.hpp
@@ -0,0 +1,250 @@
+/** \file
+ * \brief Defines the interface for a common token.
+ *
+ * All token streams should provide their tokens using an instance
+ * of this common token. A custom pointer is provided, wher you may attach
+ * a further structure to enhance the common token if you feel the need
+ * to do so. The C runtime will assume that a token provides implementations
+ * of the interface functions, but all of them may be rplaced by your own
+ * implementation if you require it.
+ */
+#ifndef	_ANTLR3_COMMON_TOKEN_HPP
+#define	_ANTLR3_COMMON_TOKEN_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    <stdlib.h>
+
+#include    "antlr3defs.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+/** The definition of an ANTLR3 common token structure, which all implementations
+ * of a token stream should provide, installing any further structures in the
+ * custom pointer element of this structure.
+ *
+ * \remark
+ * Token streams are in essence provided by lexers or other programs that serve
+ * as lexers.
+ */
+
+template<class ImplTraits>
+class CommonToken : public ImplTraits::AllocPolicyType
+{
+public:
+	/* Base token types, which all lexer/parser tokens come after in sequence.
+	*/
+	enum TOKEN_TYPE
+	{
+		/** Indicator of an invalid token
+		 */
+		TOKEN_INVALID =	0
+		, EOR_TOKEN_TYPE	
+		/** Imaginary token type to cause a traversal of child nodes in a tree parser
+		 */
+		, TOKEN_DOWN		
+		/** Imaginary token type to signal the end of a stream of child nodes.
+		 */
+		, TOKEN_UP	
+		/** First token that can be used by users/generated code
+		 */
+		, MIN_TOKEN_TYPE =	TOKEN_UP + 1
+
+		/** End of file token
+		 */
+		, TOKEN_EOF =	(ANTLR_CHARSTREAM_EOF & 0xFFFFFFFF)
+	};
+
+	typedef typename ImplTraits::TokenIntStreamType TokenIntStreamType;
+	typedef typename ImplTraits::StringType StringType;
+	typedef typename ImplTraits::InputStreamType InputStreamType;
+	typedef typename ImplTraits::StreamDataType StreamDataType;
+
+private:
+    /** The actual type of this token
+     */
+    ANTLR_UINT32   m_type;
+
+	/** The virtual channel that this token exists in.
+     */
+    ANTLR_UINT32	m_channel;
+	
+	mutable StringType		m_tokText;
+
+    /** The offset into the input stream that the line in which this
+     *  token resides starts.
+     */
+	const StreamDataType*	m_lineStart;
+
+	/** The line number in the input stream where this token was derived from
+     */
+    ANTLR_UINT32	m_line;
+
+    /** The character position in the line that this token was derived from
+     */
+    ANTLR_INT32		m_charPositionInLine;
+
+    /** Pointer to the input stream that this token originated in.
+     */
+    InputStreamType*    m_input;
+
+    /** What the index of this token is, 0, 1, .., n-2, n-1 tokens
+     */
+    ANTLR_MARKER		m_index;
+
+    /** The character offset in the input stream where the text for this token
+     *  starts.
+     */
+    ANTLR_MARKER		m_startIndex;
+
+    /** The character offset in the input stream where the text for this token
+     *  stops.
+     */
+    ANTLR_MARKER		m_stopIndex;
+
+public:
+	CommonToken();
+	CommonToken(ANTLR_UINT32 type);
+	CommonToken(TOKEN_TYPE type);
+	CommonToken( const CommonToken& ctoken );
+
+	CommonToken& operator=( const CommonToken& ctoken );
+	bool operator==( const CommonToken& ctoken ) const;
+	bool operator<( const CommonToken& ctoken ) const;
+
+	InputStreamType* get_input() const;
+	ANTLR_MARKER get_index() const;
+	void set_index( ANTLR_MARKER index );
+	void set_input( InputStreamType* input );
+
+    /* ==============================
+     * API 
+     */
+
+    /** Function that returns the text pointer of a token, use
+     *  toString() if you want a pANTLR3_STRING version of the token.
+     */
+    StringType  getText() const;
+	
+    /** Pointer to a function that 'might' be able to set the text associated
+     *  with a token. Imaginary tokens such as an ANTLR3_CLASSIC_TOKEN may actually
+     *  do this, however many tokens such as ANTLR3_COMMON_TOKEN do not actaully have
+     *  strings associated with them but just point into the current input stream. These
+     *  tokens will implement this function with a function that errors out (probably
+     *  drastically.
+     */
+    void set_tokText( const StringType& text );
+
+    /** Pointer to a function that 'might' be able to set the text associated
+     *  with a token. Imaginary tokens such as an ANTLR3_CLASSIC_TOKEN may actually
+     *  do this, however many tokens such as ANTLR3_COMMON_TOKEN do not actully have
+     *  strings associated with them but just point into the current input stream. These
+     *  tokens will implement this function with a function that errors out (probably
+     *  drastically.
+     */
+    void	setText(ANTLR_UINT8* text);
+	void	setText(const char* text);
+
+    /** Pointer to a function that returns the token type of this token
+     */
+    ANTLR_UINT32  get_type() const;
+	ANTLR_UINT32  getType() const;
+
+    /** Pointer to a function that sets the type of this token
+     */
+    void	set_type(ANTLR_UINT32 ttype);
+
+    /** Pointer to a function that gets the 'line' number where this token resides
+     */
+    ANTLR_UINT32   get_line() const;
+
+    /** Pointer to a function that sets the 'line' number where this token reside
+     */
+    void set_line(ANTLR_UINT32 line);
+
+    /** Pointer to a function that gets the offset in the line where this token exists
+     */ 
+    ANTLR_INT32  get_charPositionInLine() const;
+	ANTLR_INT32  getCharPositionInLine() const;
+
+    /** Pointer to a function that sets the offset in the line where this token exists
+     */
+    void	set_charPositionInLine(ANTLR_INT32 pos);
+
+    /** Pointer to a function that gets the channel that this token was placed in (parsers
+     *  can 'tune' to these channels.
+     */
+    ANTLR_UINT32   get_channel() const;
+
+    /** Pointer to a function that sets the channel that this token should belong to
+     */
+    void set_channel(ANTLR_UINT32 channel);
+
+    /** Pointer to a function that returns an index 0...n-1 of the token in the token
+     *  input stream.
+     */
+    ANTLR_MARKER  get_tokenIndex() const;
+
+    /** Pointer to a function that can set the token index of this token in the token
+     *  input stream.
+     */
+    void	set_tokenIndex(ANTLR_MARKER tokenIndex);
+
+    /** Pointer to a function that gets the start index in the input stream for this token.
+     */
+    ANTLR_MARKER   get_startIndex() const;
+
+    /** Pointer to a function that sets the start index in the input stream for this token.
+     */
+    void	set_startIndex(ANTLR_MARKER index);
+    
+    /** Pointer to a function that gets the stop index in the input stream for this token.
+     */
+    ANTLR_MARKER  get_stopIndex() const;
+
+    /** Pointer to a function that sets the stop index in the input stream for this token.
+     */
+    void	set_stopIndex(ANTLR_MARKER index);
+	const StreamDataType* get_lineStart() const;
+	void	set_lineStart( const StreamDataType* lineStart );
+
+    /** Pointer to a function that returns this token as a text representation that can be 
+     *  printed with embedded control codes such as \n replaced with the printable sequence "\\n"
+     *  This also yields a string structure that can be used more easily than the pointer to 
+     *  the input stream in certain situations.
+     */
+    StringType  toString() const;
+
+};
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3commontoken.inl"
+
+#endif
diff --git a/runtime/Cpp/include/antlr3commontoken.inl b/runtime/Cpp/include/antlr3commontoken.inl
new file mode 100755
index 0000000..87194dc
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontoken.inl
@@ -0,0 +1,322 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template<class ImplTraits>
+CommonToken<ImplTraits>::CommonToken()
+{
+	m_type = 0;
+    m_channel = 0;
+	m_lineStart = NULL;
+	m_line = 0;
+	m_charPositionInLine = 0;
+	m_input = NULL;
+	m_index = 0;
+	m_startIndex = 0;
+	m_stopIndex = 0;
+}
+
+template<class ImplTraits>
+CommonToken<ImplTraits>::CommonToken(ANTLR_UINT32 type)
+{
+	m_type = type;
+	m_channel = 0;
+	m_lineStart = NULL;
+	m_line = 0;
+	m_charPositionInLine = 0;
+	m_input = NULL;
+	m_index = 0;
+	m_startIndex = 0;
+	m_stopIndex = 0;
+}
+
+template<class ImplTraits>
+CommonToken<ImplTraits>::CommonToken(TOKEN_TYPE type)
+{
+	m_type = type;
+	m_channel = 0;
+	m_lineStart = NULL;
+	m_line = 0;
+	m_charPositionInLine = 0;
+	m_input = NULL;
+	m_index = 0;
+	m_startIndex = 0;
+	m_stopIndex = 0;
+}
+
+template<class ImplTraits>
+CommonToken<ImplTraits>::CommonToken( const CommonToken& ctoken )
+	:m_tokText( ctoken.m_tokText )
+{
+	m_type = ctoken.m_type;
+	m_channel = ctoken.m_channel;
+	m_lineStart = ctoken.m_lineStart;
+	m_line = ctoken.m_line;
+	m_charPositionInLine = ctoken.m_charPositionInLine;
+	m_input = ctoken.m_input;
+	m_index = ctoken.m_index;
+	m_startIndex = ctoken.m_startIndex;
+	m_stopIndex = ctoken.m_stopIndex;
+}
+
+template<class ImplTraits>
+CommonToken<ImplTraits>& CommonToken<ImplTraits>::operator=( const CommonToken& ctoken )
+{
+	m_type = ctoken.m_type;
+	m_channel = ctoken.m_channel;
+	m_lineStart = ctoken.m_lineStart;
+	m_line = ctoken.m_line;
+	m_charPositionInLine = ctoken.m_charPositionInLine;
+	m_input = ctoken.m_input;
+	m_index = ctoken.m_index;
+	m_startIndex = ctoken.m_startIndex;
+	m_stopIndex = ctoken.m_stopIndex;
+
+	m_tokText = ctoken.m_tokText;
+	return *this;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE bool CommonToken<ImplTraits>::operator<( const CommonToken& ctoken ) const
+{
+	return (m_index < ctoken.m_index);
+}
+
+template<class ImplTraits>
+bool CommonToken<ImplTraits>::operator==( const CommonToken& ctoken ) const
+{
+	return ( (m_type == ctoken.m_type) &&
+		     (m_channel == ctoken.m_channel) &&
+			 (m_lineStart == ctoken.m_lineStart) &&
+			 (m_line == ctoken.m_line) &&
+			 (m_charPositionInLine == ctoken.m_charPositionInLine) &&
+			 (m_input == ctoken.m_input) &&
+			 (m_index == ctoken.m_index) &&
+			 (m_startIndex == ctoken.m_startIndex) &&
+			 (m_stopIndex == ctoken.m_stopIndex) );
+}
+
+template<class ImplTraits>
+ANTLR_INLINE typename CommonToken<ImplTraits>::InputStreamType* CommonToken<ImplTraits>::get_input() const
+{
+	return m_input;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_MARKER CommonToken<ImplTraits>::get_index() const
+{
+	return m_index;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void CommonToken<ImplTraits>::set_index( ANTLR_MARKER index )
+{
+	m_index = index;
+}
+
+template<class ImplTraits>
+void CommonToken<ImplTraits>::set_input( InputStreamType* input )
+{
+	m_input = input;
+}
+
+template<class ImplTraits>
+typename CommonToken<ImplTraits>::StringType  CommonToken<ImplTraits>::getText() const
+{
+	if ( !m_tokText.empty() )
+		return m_tokText;
+
+	// EOF is a special case
+	//
+	if ( m_type == TOKEN_EOF)
+	{
+		m_tokText	= "<EOF>";
+		return m_tokText;
+	}
+
+	// We had nothing installed in the token, create a new string
+	// from the input stream
+	//
+	if	(m_input != NULL)
+		return	m_input->substr(	this->get_startIndex(), this->get_stopIndex() );
+
+	// Nothing to return, there is no input stream
+	//
+	return "";
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void CommonToken<ImplTraits>::set_tokText( const StringType& text )
+{
+	m_tokText = text;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void CommonToken<ImplTraits>::setText(ANTLR_UINT8* text)
+{
+	if( text == NULL )
+		m_tokText.clear();
+	else
+		m_tokText = (const char*) text;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::setText(const char* text)
+{
+	if( text == NULL )
+		m_tokText.clear();
+	else
+		m_tokText = (const char*) text;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32  CommonToken<ImplTraits>::get_type() const
+{
+	return m_type;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32  CommonToken<ImplTraits>::getType() const
+{
+	return m_type;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_type(ANTLR_UINT32 ttype)
+{
+	m_type = ttype;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32   CommonToken<ImplTraits>::get_line() const
+{
+	return m_line;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void CommonToken<ImplTraits>::set_line(ANTLR_UINT32 line)
+{
+	m_line = line;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_INT32  CommonToken<ImplTraits>::get_charPositionInLine() const
+{
+	return m_charPositionInLine;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_INT32  CommonToken<ImplTraits>::getCharPositionInLine() const
+{
+	return this->get_charPositionInLine();
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_charPositionInLine(ANTLR_INT32 pos)
+{
+	m_charPositionInLine = pos;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_UINT32   CommonToken<ImplTraits>::get_channel() const
+{
+	return m_channel;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void CommonToken<ImplTraits>::set_channel(ANTLR_UINT32 channel)
+{
+	m_channel = channel;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_MARKER  CommonToken<ImplTraits>::get_tokenIndex() const
+{
+	return m_index;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_tokenIndex(ANTLR_MARKER tokenIndex)
+{
+	m_index = tokenIndex;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_MARKER   CommonToken<ImplTraits>::get_startIndex() const
+{
+	return (m_startIndex == -1) ? (ANTLR_MARKER)(m_input->get_data()) : m_startIndex;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_startIndex(ANTLR_MARKER index)
+{
+	m_startIndex = index;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE ANTLR_MARKER  CommonToken<ImplTraits>::get_stopIndex() const
+{
+	return m_stopIndex;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_stopIndex(ANTLR_MARKER index)
+{
+	m_stopIndex = index;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE const typename CommonToken<ImplTraits>::StreamDataType* CommonToken<ImplTraits>::get_lineStart() const
+{
+	return m_lineStart;
+}
+
+template<class ImplTraits>
+ANTLR_INLINE void	CommonToken<ImplTraits>::set_lineStart( const StreamDataType* lineStart )
+{
+	m_lineStart = lineStart;
+}
+
+template<class ImplTraits>
+typename CommonToken<ImplTraits>::StringType  CommonToken<ImplTraits>::toString() const
+{
+    StringType  text;
+    typedef typename ImplTraits::StringStreamType StringStreamType;
+    StringStreamType  outtext; 
+
+    text    =	this->getText();
+
+    if	(text.empty())
+		return "";
+
+    /* Now we use our handy dandy string utility to assemble the
+     * the reporting string
+     * return "[@"+getTokenIndex()+","+start+":"+stop+"='"+txt+"',<"+type+">"+channelStr+","+line+":"+getCharPositionInLine()+"]";
+     */
+    outtext << "[Index: ";
+    outtext << (int)this->get_tokenIndex();
+    outtext << " (Start: ";
+    outtext << (int)this->get_startIndex();
+    outtext << "-Stop: ";
+    outtext << (int)this->get_stopIndex();
+    outtext << ") ='";
+    outtext << text;
+    outtext << "', type<";
+    outtext << (int)m_type;
+    outtext << "> ";
+
+    if	(this->get_channel() > TOKEN_DEFAULT_CHANNEL)
+    {
+		outtext << "(channel = ";
+		outtext << (int)this->get_channel();
+		outtext << ") ";
+    }
+
+    outtext << "Line: ";
+    outtext << (int)this->get_line();
+    outtext << " LinePos:";
+    outtext << (int)this->get_charPositionInLine();
+    outtext << "]";
+
+    return  outtext.str();
+}
+
+ANTLR_END_NAMESPACE()
diff --git a/runtime/Cpp/include/antlr3commontree.hpp b/runtime/Cpp/include/antlr3commontree.hpp
new file mode 100755
index 0000000..39096f8
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontree.hpp
@@ -0,0 +1,139 @@
+/** Interface for an ANTLR3 common tree which is what gets
+ *  passed around by the AST producing parser.
+ */
+
+#ifndef	_ANTLR3_COMMON_TREE_HPP
+#define	_ANTLR3_COMMON_TREE_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    "antlr3defs.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+template<class ImplTraits>
+class CommonTree : public ImplTraits::AllocPolicyType				   
+{
+public:
+	typedef typename ImplTraits::AllocPolicyType AllocPolicyType;
+	typedef typename ImplTraits::StringType	StringType;
+	typedef typename ImplTraits::CommonTokenType CommonTokenType;
+	typedef typename ImplTraits::TreeType TreeType;
+	typedef CommonTree TokenType;
+	typedef typename AllocPolicyType::template VectorType<TreeType*> ChildrenType;
+	typedef typename AllocPolicyType::template ListType<TreeType*>	ChildListType;
+
+private:
+	/// The list of all the children that belong to this node. They are not part of the node
+    /// as they belong to the common tree node that implements this.
+    ///
+    ChildrenType		m_children;
+
+    /// This is used to store the current child index position while descending
+    /// and ascending trees as the tree walk progresses.
+    ///
+    ANTLR_MARKER		m_savedIndex;
+
+    /// Start token index that encases this tree
+    ///
+    ANTLR_MARKER		m_startIndex;
+
+    /// End token that encases this tree
+    ///
+    ANTLR_MARKER		m_stopIndex;
+
+    /// A single token, this is the payload for the tree
+    ///
+    CommonTokenType*    m_token;
+
+	/// Points to the node that has this node as a child.
+	/// If this is NULL, then this is the root node.
+	///
+	CommonTree*			m_parent;
+
+	/// What index is this particular node in the child list it
+	/// belongs to?
+	///
+	ANTLR_INT32			m_childIndex;
+
+public:
+	CommonTree();
+	CommonTree( CommonTokenType* token );
+	CommonTree( CommonTree* token );
+	CommonTree( const CommonTree& ctree );
+
+	TokenType*   get_token() const;
+	ChildrenType& get_children();
+	const ChildrenType& get_children() const;
+	ChildrenType* get_children_p();
+	ANTLR_INT32	get_childIndex() const;
+	TreeType* get_parent() const;
+
+	void    set_parent( TreeType* parent);
+	void    set_childIndex( ANTLR_INT32 );
+
+	void	addChild(TreeType* child);
+	/// Add all elements of the supplied list as children of this node
+	///
+	void	addChildren(const ChildListType& kids);
+	void    createChildrenList();
+	TreeType*	deleteChild(ANTLR_UINT32 i);
+	/// Delete children from start to stop and replace with t even if t is
+	/// a list (nil-root tree). Num of children can increase or decrease.
+	/// For huge child lists, inserting children can force walking rest of
+	/// children to set their child index; could be slow.
+	///
+	void	replaceChildren(ANTLR_INT32 startChildIndex, ANTLR_INT32 stopChildIndex, TreeType* t);
+	CommonTree*	dupNode() const;
+	TreeType*	dupTree();
+	ANTLR_UINT32	getCharPositionInLine();
+	TreeType*	getChild(ANTLR_UINT32 i);
+	
+	ANTLR_UINT32	getChildCount() const;
+	ANTLR_UINT32	getType();
+	TreeType*	getFirstChildWithType(ANTLR_UINT32 type);
+	ANTLR_UINT32	getLine();
+	StringType	getText();
+	bool	isNilNode();
+	void	setChild(ANTLR_UINT32 i, TreeType* child);
+	StringType	toStringTree();
+	StringType	toString();
+	void	freshenPACIndexesAll();
+	void	freshenPACIndexes(ANTLR_UINT32 offset);
+	void    reuse();
+	~CommonTree();
+};
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3commontree.inl"
+
+#endif
+
+
diff --git a/runtime/Cpp/include/antlr3commontree.inl b/runtime/Cpp/include/antlr3commontree.inl
new file mode 100755
index 0000000..8a3111b
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontree.inl
@@ -0,0 +1,565 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template<class ImplTraits>
+CommonTree<ImplTraits>::CommonTree()
+{
+	m_savedIndex = 0;
+	m_startIndex = 0;
+	m_stopIndex  = 0;
+	m_token		 = NULL;
+	m_parent     = NULL;
+	m_childIndex = 0;
+}
+
+template<class ImplTraits>
+CommonTree<ImplTraits>::CommonTree( const CommonTree& ctree )
+	:m_children( ctree.m_children)
+{
+	m_savedIndex = ctree.m_savedIndex;
+	m_startIndex = ctree.m_startIndex;
+	m_stopIndex  = ctree.m_stopIndex;
+	m_token		 = ctree.m_token;
+	m_parent     = ctree.m_parent;
+	m_childIndex = ctree.m_childIndex;
+}
+
+template<class ImplTraits>
+CommonTree<ImplTraits>::CommonTree( CommonTokenType* token )
+{
+	m_savedIndex = 0;
+	m_startIndex = 0;
+	m_stopIndex  = 0;
+	m_token		 = token;
+	m_parent     = NULL;
+	m_childIndex = 0;
+}
+
+template<class ImplTraits>
+CommonTree<ImplTraits>::CommonTree( CommonTree* tree )
+{
+	m_savedIndex = 0;
+	m_startIndex = 0;
+	m_stopIndex  = 0;
+	m_token		 = tree->get_token();
+	m_parent     = NULL;
+	m_childIndex = 0;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TokenType*   CommonTree<ImplTraits>::get_token() const
+{
+	return m_token;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::ChildrenType& CommonTree<ImplTraits>::get_children()
+{
+	return m_children;
+}
+
+template<class ImplTraits>
+const typename CommonTree<ImplTraits>::ChildrenType& CommonTree<ImplTraits>::get_children() const
+{
+	return m_children;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::ChildrenType* CommonTree<ImplTraits>::get_children_p()
+{
+	return &m_children;
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::addChild(TreeType* child)
+{
+	ANTLR_UINT32   n;
+	ANTLR_UINT32   i;
+
+	if	(child == NULL)
+		return;
+
+	ChildrenType& child_children = child->get_children();
+	ChildrenType& tree_children  = this->get_children();
+
+	if	(child->isNilNode() == true)
+	{
+		if ( !child_children.empty() && child_children == tree_children )
+		{
+			// TODO: Change to exception rather than ANTLR3_FPRINTF?
+			//
+			fprintf(stderr, "ANTLR3: An attempt was made to add a child list to itself!\n");
+			return;
+		}
+
+        // Add all of the children's children to this list
+        //
+        if ( !child_children.empty() )
+        {
+            if (tree_children.empty())
+            {
+                // We are build ing the tree structure here, so we need not
+                // worry about duplication of pointers as the tree node
+                // factory will only clean up each node once. So we just
+                // copy in the child's children pointer as the child is
+                // a nil node (has not root itself).
+                //
+                tree_children.swap( child_children );
+                this->freshenPACIndexesAll();               
+            }
+            else
+            {
+                // Need to copy the children
+                //
+                n = child_children.size();
+
+                for (i = 0; i < n; i++)
+                {
+                    TreeType* entry;
+                    entry = child_children[i];
+
+                    // ANTLR3 lists can be sparse, unlike Array Lists
+                    //
+                    if (entry != NULL)
+                    {
+                        tree_children.push_back(entry);
+                    }
+                }
+            }
+		}
+	}
+	else
+	{
+		// Tree we are adding is not a Nil and might have children to copy
+		//
+		if  (tree_children.empty())
+		{
+			// No children in the tree we are adding to, so create a new list on
+			// the fly to hold them.
+			//
+			this->createChildrenList();
+		}
+		tree_children.push_back( child );
+	}
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::addChildren(const ChildListType& kids)
+{
+	for( typename ChildListType::const_iterator iter = kids.begin();
+		 iter != kids.end(); ++iter )
+	{
+		this->addChild( *iter );
+	}
+}
+
+//dummy one, as vector is always there
+template<class ImplTraits>
+void    CommonTree<ImplTraits>::createChildrenList()
+{
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TreeType*	CommonTree<ImplTraits>::deleteChild(ANTLR_UINT32 i)
+{
+	if( m_children.empty() )
+		return	NULL;
+
+	return  m_children.erase( m_children.begin() + i);
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::replaceChildren(ANTLR_INT32 startChildIndex, ANTLR_INT32 stopChildIndex, TreeType* newTree)
+{
+	ANTLR_INT32	replacingHowMany;		// How many nodes will go away
+	ANTLR_INT32	replacingWithHowMany;	// How many nodes will replace them
+	ANTLR_INT32	numNewChildren;			// Tracking variable
+	ANTLR_INT32	delta;					// Difference in new vs existing count
+
+	ANTLR_INT32	i;
+	ANTLR_INT32	j;
+
+	if	( m_children.empty() )
+	{
+		fprintf(stderr, "replaceChildren call: Indexes are invalid; no children in list for %s", this->getText().c_str() );
+		return;
+	}
+
+	// Either use the existing list of children in the supplied nil node, or build a vector of the
+	// tree we were given if it is not a nil node, then we treat both situations exactly the same
+	//
+	ChildrenType newChildren_temp;
+	ChildrenType*	newChildren;			// Iterator for whatever we are going to add in
+
+	if	(newTree->isNilNode())
+	{
+		newChildren = newTree->get_children_p();
+	}
+	else
+	{
+		newChildren = &newChildren_temp;
+		newChildren->push_back(newTree);
+	}
+
+	// Initialize
+	//
+	replacingHowMany		= stopChildIndex - startChildIndex + 1;
+	replacingWithHowMany	= newChildren->size();
+	delta					= replacingHowMany - replacingWithHowMany;
+	numNewChildren			= newChildren->size();
+
+	// If it is the same number of nodes, then do a direct replacement
+	//
+	if	(delta == 0)
+	{
+		TreeType*	child;
+
+		// Same number of nodes
+		//
+		j	= 0;
+		for	(i = startChildIndex; i <= stopChildIndex; i++)
+		{
+			child = newChildren->at(j);
+			ChildrenType& parent_children = this->get_children();
+			parent_children[i] = child;
+			child->setParent(this);
+			child->setChildIndex(i);
+		}
+	}
+	else if (delta > 0)
+	{
+		ANTLR_UINT32	indexToDelete;
+
+		// Less nodes than there were before
+		// reuse what we have then delete the rest
+		//
+		ChildrenType& parent_children = this->get_children();
+		for	(j = 0; j < numNewChildren; j++)
+		{
+			parent_children[ startChildIndex + j ] = newChildren->at(j);
+		}
+
+		// We just delete the same index position until done
+		//
+		indexToDelete = startChildIndex + numNewChildren;
+
+		for	(j = indexToDelete; j <= stopChildIndex; j++)
+		{
+			parent_children.erase( parent_children.begin() + indexToDelete);
+		}
+
+		this->freshenPACIndexes(startChildIndex);
+	}
+	else
+	{
+		ChildrenType& parent_children = this->get_children();
+		ANTLR_UINT32 numToInsert;
+
+		// More nodes than there were before
+		// Use what we can, then start adding
+		//
+		for	(j = 0; j < replacingHowMany; j++)
+		{
+			parent_children[ startChildIndex + j ] = newChildren->at(j);
+		}
+
+		numToInsert = replacingWithHowMany - replacingHowMany;
+
+		for	(j = replacingHowMany; j < replacingWithHowMany; j++)
+		{
+			parent_children.push_back( newChildren->at(j) );
+		}
+
+		this->freshenPACIndexes(startChildIndex);
+	}
+}
+
+template<class ImplTraits>
+CommonTree<ImplTraits>*	CommonTree<ImplTraits>::dupNode() const
+{
+	// The node we are duplicating is in fact the common tree (that's why we are here)
+    // so we use the super pointer to duplicate.
+    //
+    TreeType*   clone = new TreeType();
+
+	// The pointer we return is the base implementation of course
+    //
+	clone->set_token( m_token );
+	return  clone;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TreeType*	CommonTree<ImplTraits>::dupTree()
+{
+	TreeType*	newTree;
+	ANTLR_UINT32	i;
+	ANTLR_UINT32	s;
+
+	newTree = this->dupNode();
+
+	if	( !m_children.empty() )
+	{
+		s	    = m_children.size();
+
+		for	(i = 0; i < s; i++)
+		{
+			TreeType*    t;
+			TreeType*    newNode;
+
+			t   = m_children[i];
+
+			if  (t!= NULL)
+			{
+				newNode	    = t->dupTree();
+				newTree->addChild(newNode);
+			}
+		}
+	}
+
+	return newTree;
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTree<ImplTraits>::getCharPositionInLine()
+{
+	CommonTokenType*    token;
+	token   = m_token;
+
+	if	(token == NULL || (token->getCharPositionInLine() == -1) )
+	{
+		if  (this->getChildCount() > 0)
+		{
+			TreeType*	child;
+
+			child   = this->getChild(0);
+
+			return child->getCharPositionInLine();
+		}
+		return 0;
+	}
+	return  token->getCharPositionInLine();
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TreeType*	CommonTree<ImplTraits>::getChild(ANTLR_UINT32 i)
+{
+	if	(  m_children.empty()
+		|| i >= m_children.size() )
+	{
+		return NULL;
+	}
+	return  m_children[i];
+
+}
+
+template<class ImplTraits>
+void    CommonTree<ImplTraits>::set_childIndex( ANTLR_INT32 i)
+{
+	m_childIndex = i;
+}
+
+template<class ImplTraits>
+ANTLR_INT32	CommonTree<ImplTraits>::get_childIndex() const
+{
+	return m_childIndex;
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTree<ImplTraits>::getChildCount() const
+{
+	return static_cast<ANTLR_UINT32>( m_children.size() );
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TreeType* CommonTree<ImplTraits>::get_parent() const
+{
+	return m_parent;
+}
+
+template<class ImplTraits>
+void     CommonTree<ImplTraits>::set_parent( TreeType* parent)
+{
+	m_parent = parent;
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTree<ImplTraits>::getType()
+{
+	if	(this == NULL)
+	{
+		return	0;
+	}
+	else
+	{
+		return	m_token->getType();
+	}
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::TreeType*	CommonTree<ImplTraits>::getFirstChildWithType(ANTLR_UINT32 type)
+{
+	ANTLR_UINT32   i;
+	std::size_t   cs;
+
+	TreeType*	t;
+	if	( !m_children.empty() )
+	{
+		cs	= m_children.size();
+		for	(i = 0; i < cs; i++)
+		{
+			t = m_children[i];
+			if  (t->getType() == type)
+			{
+				return  t;
+			}
+		}
+	}
+	return  NULL;
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTree<ImplTraits>::getLine()
+{
+	TreeType*	    cTree = this;
+	CommonTokenType* token;
+	token   = cTree->get_token();
+
+	if	(token == NULL || token->getLine() == 0)
+	{
+		if  ( this->getChildCount() > 0)
+		{
+			TreeType*	child;
+			child   = this->getChild(0);
+			return child->getLine();
+		}
+		return 0;
+	}
+	return  token->getLine();
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::StringType	CommonTree<ImplTraits>::getText()
+{
+	return this->toString();
+}
+
+template<class ImplTraits>
+bool	CommonTree<ImplTraits>::isNilNode()
+{
+	// This is a Nil tree if it has no payload (Token in our case)
+	//
+	if(m_token == NULL)
+	{
+		return true;
+	}
+	else
+	{
+		return false;
+	}
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::setChild(ANTLR_UINT32 i, TreeType* child)
+{
+	if( m_children.size() >= i )
+		m_children.resize(i+1);
+	m_children[i] = child;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::StringType	CommonTree<ImplTraits>::toStringTree()
+{
+	StringType  string;
+	ANTLR_UINT32   i;
+	ANTLR_UINT32   n;
+	TreeType*   t;
+
+	if( m_children.empty() )
+	{
+		return	this->toString();
+	}
+
+	/* Need a new string with nothing at all in it.
+	*/
+	if	(this->isNilNode() == false)
+	{
+		string.append("(");
+		string.append(this->toString());
+		string.append(" ");
+	}
+	if	( m_children != NULL)
+	{
+		n = m_children.size();
+
+		for	(i = 0; i < n; i++)
+		{   
+			t   = m_children[i];
+
+			if  (i > 0)
+			{
+				string.append(" ");
+			}
+			string.append(t->toStringTree());
+		}
+	}
+	if	(this->isNilNode() == false)
+	{
+		string.append(")");
+	}
+
+	return  string;
+}
+
+template<class ImplTraits>
+typename CommonTree<ImplTraits>::StringType	CommonTree<ImplTraits>::toString()
+{
+	if  (this->isNilNode() )
+	{
+		StringType  nilNode;
+
+		nilNode	= "nil";
+
+		return nilNode;
+	}
+
+	return	m_token->getText();
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::freshenPACIndexesAll()
+{
+	this->freshenPACIndexes(0);
+}
+
+template<class ImplTraits>
+void	CommonTree<ImplTraits>::freshenPACIndexes(ANTLR_UINT32 offset)
+{
+	ANTLR_UINT32	count;
+	ANTLR_UINT32	c;
+
+	count	= this->getChildCount();		// How many children do we have 
+
+	// Loop from the supplied index and set the indexes and parent
+	//
+	for	(c = offset; c < count; c++)
+	{
+		TreeType*	child;
+
+		child = this->getChild(c);
+
+		child->setChildIndex(c);
+		child->setParent(this);
+	}
+}
+
+template<class ImplTraits>
+void    CommonTree<ImplTraits>::reuse()
+{
+	delete this; //memory re-use should be taken by the library user
+}
+
+template<class ImplTraits>
+CommonTree<ImplTraits>::~CommonTree()
+{
+}
+
+ANTLR_END_NAMESPACE()
diff --git a/runtime/Cpp/include/antlr3commontreeadaptor.hpp b/runtime/Cpp/include/antlr3commontreeadaptor.hpp
new file mode 100755
index 0000000..8b40f1c
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontreeadaptor.hpp
@@ -0,0 +1,163 @@
+/** \file
+ * Definition of the ANTLR3 common tree adaptor.
+ */
+
+#ifndef	_ANTLR3_COMMON_TREE_ADAPTOR_HPP
+#define	_ANTLR3_COMMON_TREE_ADAPTOR_HPP
+
+// [The "BSD licence"]
+// Copyright (c) 2005-2009 Gokulakannan Somasundaram, ElectronDB
+
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+//    derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include    "antlr3defs.hpp"
+
+ANTLR_BEGIN_NAMESPACE()
+
+template<class ImplTraits>
+class CommonTreeAdaptor : public ImplTraits::AllocPolicyType
+{
+public:
+	typedef typename ImplTraits::StringType StringType;
+	typedef typename ImplTraits::TreeType TreeType;
+	typedef	TreeType TokenType;
+	typedef typename ImplTraits::CommonTokenType CommonTokenType;
+	typedef typename ImplTraits::DebugEventListenerType DebuggerType;
+
+public:
+	//The parameter is there only to provide uniform constructor interface
+	CommonTreeAdaptor(DebuggerType* dbg = NULL);
+    TreeType*	  nilNode();
+	TreeType*	  dupTree( TreeType* tree);
+    TreeType*	  dupTreeTT( TreeType* t, TreeType* tree);
+
+    void	addChild( TreeType* t, TreeType* child);
+    void	addChildToken( TreeType* t, CommonTokenType* child);
+    void	setParent( TreeType* child, TreeType* parent);
+    TreeType*		getParent( TreeType* child);
+
+	TreeType*		errorNode( CommonTokenType* tnstream, CommonTokenType* startToken, CommonTokenType* stopToken);
+	bool	isNilNode( TreeType* t);
+
+    TreeType*	    becomeRoot( TreeType* newRoot, TreeType* oldRoot);
+    TreeType*	   	rulePostProcessing( TreeType* root);
+
+    TreeType*	becomeRootToken(CommonTokenType* newRoot, TreeType* oldRoot);
+
+    TreeType*	 	create( CommonTokenType* payload);
+    TreeType* 		createTypeToken( ANTLR_UINT32 tokenType, CommonTokenType* fromToken);
+    TreeType*	   	createTypeTokenText	( ANTLR_UINT32 tokenType, CommonTokenType* fromToken, const ANTLR_UINT8* text);
+    TreeType*	    createTypeText		( ANTLR_UINT32 tokenType, const ANTLR_UINT8* text);
+
+    TreeType*	    dupNode( TreeType* treeNode);
+    ANTLR_UINT32			getType( TreeType* t);
+    StringType			getText( TreeType* t);
+        
+    TreeType*	    getChild( TreeType* t, ANTLR_UINT32 i);
+    void	setChild( TreeType* t, ANTLR_UINT32 i, TreeType* child);
+    void	deleteChild( TreeType* t, ANTLR_UINT32 i);
+    void	setChildIndex( TreeType* t, ANTLR_INT32 i);
+    ANTLR_INT32	getChildIndex( TreeType* t);
+
+    ANTLR_UINT32	getChildCount( TreeType*);
+	ANTLR_UINT64	getUniqueID( TreeType*);
+
+    CommonTokenType*    createToken( ANTLR_UINT32 tokenType, const ANTLR_UINT8* text);
+    CommonTokenType*    createTokenFromToken( CommonTokenType* fromToken);
+    CommonTokenType*    getToken( TreeType* t);
+
+    void setTokenBoundaries( TreeType* t, CommonTokenType* startToken, CommonTokenType* stopToken);
+    ANTLR_MARKER	getTokenStartIndex( TreeType* t);
+    ANTLR_MARKER	getTokenStopIndex( TreeType* t);
+
+	/// Produce a DOT (see graphviz freeware suite) from a base tree
+	///
+	StringType			makeDot( TreeType* theTree);
+
+	/// Replace from start to stop child index of parent with t, which might
+	/// be a list.  Number of children may be different
+	/// after this call.
+	///
+	/// If parent is null, don't do anything; must be at root of overall tree.
+	/// Can't replace whatever points to the parent externally.  Do nothing.
+	///
+	void replaceChildren( TreeType* parent, ANTLR_INT32 startChildIndex,
+								  ANTLR_INT32 stopChildIndex, TreeType* t);
+
+    ~CommonTreeAdaptor();
+
+protected:
+	void defineDotNodes(TreeType* t, const StringType& dotSpec);
+	void defineDotEdges(TreeType* t, const StringType& dotSpec);
+};
+
+//If someone can override the CommonTreeAdaptor at the compile time, that will be 
+//inherited here. Still you can choose to override the DebugTreeAdaptor, if you wish to
+//change the DebugTreeAdaptor
+template<class ImplTraits>
+class DebugTreeAdaptor : public ImplTraits::CommonTreeAdaptorType
+{
+public:
+	//DebugEventListener implements functionality through virtual functions
+	//the template parameter is required for pointing back at the adaptor
+	typedef typename ImplTraits::DebugEventListener DebuggerType;
+	typedef typename ImplTraits::TreeType TreeType;
+	typedef typename ImplTraits::CommonTokenType CommonTokenType;
+
+private:
+	/// If set to something other than NULL, then this structure is
+	/// points to an instance of the debugger interface. In general, the
+	/// debugger is only referenced internally in recovery/error operations
+	/// so that it does not cause overhead by having to check this pointer
+	/// in every function/method
+	///
+	DebuggerType*		m_debugger;
+
+public:
+	DebugTreeAdaptor( DebuggerType* debugger );
+	void setDebugEventListener( DebuggerType* debugger);
+	TreeType*	  nilNode();
+	void	addChild(TreeType* t, TreeType* child);
+	void	addChildToken(TreeType* t, CommonTokenType* child);
+	TreeType* becomeRoot( TreeType* newRootTree, TreeType* oldRootTree );
+	TreeType* becomeRootToken(TreeType* newRoot, TreeType* oldRoot);
+	TreeType* createTypeToken(ANTLR_UINT32 tokenType, CommonTokenType* fromToken);
+	TreeType* createTypeTokenText(ANTLR_UINT32 tokenType, CommonTokenType* fromToken, ANTLR_UINT8* text);	
+	TreeType* createTypeText( ANTLR_UINT32 tokenType, ANTLR_UINT8* text);
+	TreeType* dupTree( TreeType* tree);
+
+	/// Sends the required debugging events for duplicating a tree
+	/// to the debugger.
+	///
+	void simulateTreeConstruction(TreeType* tree);
+};
+
+
+ANTLR_END_NAMESPACE()
+
+#include "antlr3commontreeadaptor.inl"
+
+#endif
diff --git a/runtime/Cpp/include/antlr3commontreeadaptor.inl b/runtime/Cpp/include/antlr3commontreeadaptor.inl
new file mode 100755
index 0000000..698c7d7
--- /dev/null
+++ b/runtime/Cpp/include/antlr3commontreeadaptor.inl
@@ -0,0 +1,801 @@
+ANTLR_BEGIN_NAMESPACE()
+
+template<class ImplTraits>
+ANTLR_INLINE CommonTreeAdaptor<ImplTraits>::CommonTreeAdaptor(DebuggerType*)
+{
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	  CommonTreeAdaptor<ImplTraits>::nilNode()
+{
+	return this->create(NULL);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	  CommonTreeAdaptor<ImplTraits>::dupTree( TreeType* tree)
+{
+	return this->dupTreeTT(tree, NULL);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	  CommonTreeAdaptor<ImplTraits>::dupTreeTT( TreeType* t, TreeType* parent)
+{
+	TreeType*	newTree;
+	TreeType*	child;
+	TreeType*	newSubTree;
+	ANTLR_UINT32		n;
+	ANTLR_UINT32		i;
+
+	if	(t == NULL)
+		return NULL;
+
+	newTree = t->dupNode();
+
+	// Ensure new subtree root has parent/child index set
+	//
+	this->setChildIndex( newTree, t->getChildIndex() );
+	this->setParent(newTree, parent);
+	n = this->getChildCount(t);
+
+	for	(i=0; i < n; i++)
+	{
+		child = this->getChild(t, i);
+		newSubTree = this->dupTreeTT(child, t);
+		this->addChild(newTree, newSubTree);
+	}
+	return	newTree;
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::addChild( TreeType* t, TreeType* child)
+{
+	if	(t != NULL && child != NULL)
+	{
+		t->addChild(child);
+	}
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::addChildToken( TreeType* t, CommonTokenType* child)
+{
+	if	(t != NULL && child != NULL)
+	{
+		this->addChild(t, this->create(child));
+	}
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::setParent( TreeType* child, TreeType* parent)
+{
+	child->setParent(parent);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*		CommonTreeAdaptor<ImplTraits>::getParent( TreeType* child)
+{
+	return child->getParent();
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*		CommonTreeAdaptor<ImplTraits>::errorNode( CommonTokenType* tnstream, CommonTokenType* startToken, CommonTokenType* stopToken)
+{
+	// Use the supplied common tree node stream to get another tree from the factory
+	// TODO: Look at creating the erronode as in Java, but this is complicated by the
+	// need to track and free the memory allocated to it, so for now, we just
+	// want something in the tree that isn't a NULL pointer.
+	//
+	return this->createTypeText( CommonTokenType::TOKEN_INVALID, "Tree Error Node");
+
+}
+
+template<class ImplTraits>
+bool	CommonTreeAdaptor<ImplTraits>::isNilNode( TreeType* t)
+{
+	return t->isNilNode();
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	    CommonTreeAdaptor<ImplTraits>::becomeRoot( TreeType* newRootTree, TreeType* oldRootTree)
+{
+	TreeType* saveRoot;
+
+	/* Protect against tree rewrites if we are in some sort of error
+	 * state, but have tried to recover. In C we can end up with a null pointer
+	 * for a tree that was not produced.
+	 */
+	if	(newRootTree == NULL)
+	{
+		return	oldRootTree;
+	}
+
+	/* root is just the new tree as is if there is no
+	 * current root tree.
+	 */
+	if	(oldRootTree == NULL)
+	{
+		return	newRootTree;
+	}
+
+	/* Produce ^(nil real-node)
+	 */
+	if	(newRootTree->isNilNode())
+	{
+		if	(newRootTree->getChildCount() > 1)
+		{
+			/* TODO: Handle tree exceptions 
+			 */
+			fprintf(stderr, "More than one node as root! TODO: Create tree exception handling\n");
+			return newRootTree;
+		}
+
+		/* The new root is the first child, keep track of the original newRoot
+         * because if it was a Nil Node, then we can reuse it now.
+		 */
+        saveRoot    = newRootTree;
+		newRootTree = newRootTree->getChild(0);
+
+        // Reclaim the old nilNode()
+        //
+        saveRoot->reuse();
+	}
+
+	/* Add old root into new root. addChild takes care of the case where oldRoot
+	 * is a flat list (nill rooted tree). All children of oldroot are added to
+	 * new root.
+	 */
+	newRootTree->addChild(oldRootTree);
+
+    // If the oldroot tree was a nil node, then we know at this point
+    // it has become orphaned by the rewrite logic, so we tell it to do
+    // whatever it needs to do to be reused.
+    //
+    if  (oldRootTree->isNilNode())
+    {
+        // We have taken an old Root Tree and appended all its children to the new
+        // root. In addition though it was a nil node, which means the generated code
+        // will not reuse it again, so we will reclaim it here. First we want to zero out
+        // any pointers it was carrying around. We are just the baseTree handler so we
+        // don't know necessarilly know how to do this for the real node, we just ask the tree itself
+        // to do it.
+        //
+        oldRootTree->reuse();
+    }
+	/* Always returns new root structure
+	 */
+	return	newRootTree;
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	CommonTreeAdaptor<ImplTraits>::becomeRootToken(CommonTokenType* newRoot, TreeType* oldRoot)
+{
+	return	this->becomeRoot(this->create(newRoot), oldRoot);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	 	CommonTreeAdaptor<ImplTraits>::create( CommonTokenType* payload)
+{
+	return new TreeType(payload);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*  CommonTreeAdaptor<ImplTraits>::createTypeToken( ANTLR_UINT32 tokenType, 
+																						  CommonTokenType* fromToken)
+{
+	/* Create the new token
+	 */
+	fromToken = this->createTokenFromToken(fromToken);
+
+	/* Set the type of the new token to that supplied
+	 */
+	fromToken->setType(tokenType);
+
+	/* Return a new node based upon this token
+	 */
+	return	this->create(fromToken);
+
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	CommonTreeAdaptor<ImplTraits>::createTypeTokenText( ANTLR_UINT32 tokenType, CommonTokenType* fromToken, const ANTLR_UINT8* text)
+{
+	/* Create the new token
+	 */
+	fromToken = this->createTokenFromToken(fromToken);
+
+	/* Set the type of the new token to that supplied
+	 */
+	fromToken->setType(tokenType);
+
+	/* Set the text of the token accordingly
+	 */
+	fromToken->setText(text);
+
+	/* Return a new node based upon this token
+	 */
+	return	this->create(fromToken);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	    CommonTreeAdaptor<ImplTraits>::createTypeText( ANTLR_UINT32 tokenType, const ANTLR_UINT8* text)
+{
+	CommonTokenType*	fromToken;
+
+	/* Create the new token
+	 */
+	fromToken = this->createToken(tokenType, text);
+
+	/* Return a new node based upon this token
+	 */
+	return	this->create(fromToken);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	CommonTreeAdaptor<ImplTraits>::dupNode( TreeType* treeNode)
+{
+	return  (treeNode == NULL) ? NULL : treeNode->dupNode();
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTreeAdaptor<ImplTraits>::getType( TreeType* t)
+{
+	return t->getType();
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::StringType	CommonTreeAdaptor<ImplTraits>::getText( TreeType* t)
+{
+	return t->getText();
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::TreeType*	    CommonTreeAdaptor<ImplTraits>::getChild( TreeType* t, ANTLR_UINT32 i)
+{
+	return t->getChild(i);
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::setChild( TreeType* t, ANTLR_UINT32 i, TreeType* child)
+{
+	t->setChild(i, child);
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::deleteChild( TreeType* t, ANTLR_UINT32 i)
+{
+	t->deleteChild(i);
+}
+
+template<class ImplTraits>
+void	CommonTreeAdaptor<ImplTraits>::setChildIndex( TreeType* t, ANTLR_INT32 i)
+{
+	t->setChildIndex(i);
+}
+
+template<class ImplTraits>
+ANTLR_INT32	CommonTreeAdaptor<ImplTraits>::getChildIndex( TreeType * t)
+{
+	return t->getChildIndex();
+}
+
+template<class ImplTraits>
+ANTLR_UINT32	CommonTreeAdaptor<ImplTraits>::getChildCount( TreeType* t)
+{
+	return t->getChildCount();
+}
+
+template<class ImplTraits>
+ANTLR_UINT64	CommonTreeAdaptor<ImplTraits>::getUniqueID( TreeType* node )
+{
+	return	reinterpret_cast<ANTLR_UINT64>(node);
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::CommonTokenType*    
+	     CommonTreeAdaptor<ImplTraits>::createToken( ANTLR_UINT32 tokenType, const ANTLR_UINT8* text)
+{
+	CommonTokenType*    newToken = new CommonTokenType;
+
+    if	(newToken != NULL)
+    {	
+		newToken->set_tokText( (const char*) text );
+		newToken->setType(tokenType);
+    }
+    return  newToken;
+
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::CommonTokenType*    
+	CommonTreeAdaptor<ImplTraits>::createTokenFromToken( CommonTokenType* fromToken)
+{
+	CommonTokenType*    newToken;
+
+    newToken	= new CommonTokenType;
+    
+    if	(newToken != NULL)
+    {
+		// Create the text using our own string factory to avoid complicating
+		// commontoken.
+		//
+		StringType	text = fromToken->getText();
+		newToken->set_tokText( text );
+		newToken->setLine( fromToken->getLine() );
+		newToken->setTokenIndex( fromToken->getTokenIndex() );
+		newToken->setCharPositionInLine( fromToken->getCharPositionInLine() );
+		newToken->setChannel( fromToken->getChannel() );
+		newToken->setType( fromToken->getType() );
+    }
+
+    return  newToken;
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::CommonTokenType*  
+		 CommonTreeAdaptor<ImplTraits>::getToken( TreeType* t)
+{
+	return t->getToken();
+}
+
+template<class ImplTraits>
+void CommonTreeAdaptor<ImplTraits>::setTokenBoundaries( TreeType* t, CommonTokenType* startToken, CommonTokenType* stopToken)
+{
+	ANTLR_MARKER   start;
+	ANTLR_MARKER   stop;
+
+	TreeType*	    ct;
+
+	if	(t == NULL)
+	{
+		return;
+	}
+
+	if	( startToken != NULL)
+	{
+		start = startToken->getTokenIndex();
+	}
+	else
+	{
+		start = 0;
+	}
+
+	if	( stopToken != NULL)
+	{
+		stop = stopToken->getTokenIndex();
+	}
+	else
+	{
+		stop = 0;
+	}
+
+	ct	= t;
+
+	ct->set_startIndex(start);
+	ct->set_stopIndex(stop);
+}
+
+template<class ImplTraits>
+ANTLR_MARKER	CommonTreeAdaptor<ImplTraits>::getTokenStartIndex( TreeType* t)
+{
+	return t->get_tokenStartIndex();
+}
+
+template<class ImplTraits>
+ANTLR_MARKER	CommonTreeAdaptor<ImplTraits>::getTokenStopIndex( TreeType* t)
+{
+	return t->get_tokenStopIndex();
+}
+
+template<class ImplTraits>
+typename CommonTreeAdaptor<ImplTraits>::StringType	 CommonTreeAdaptor<ImplTraits>::makeDot( TreeType* theTree)
+{
+	// The string we are building up
+	//
+	StringType		dotSpec;
+	char            buff[64];
+	StringType      text;
+	
+	dotSpec = "digraph {\n\n"
+			"\tordering=out;\n"
+			"\tranksep=.4;\n"
+			"\tbgcolor=\"lightgrey\";  node [shape=box, fixedsize=false, fontsize=12, fontname=\"Helvetica-bold\", fontcolor=\"blue\"\n"
+			"\twidth=.25, height=.25, color=\"black\", fillcolor=\"white\", style=\"filled, solid, bold\"];\n\n"
+			"\tedge [arrowsize=.5, color=\"black\", style=\"bold\"]\n\n";
+
+    if	(theTree == NULL)
+	{
+		// No tree, so create a blank spec
+		//
+		dotSpec->append("n0[label=\"EMPTY TREE\"]\n");
+		return dotSpec;
+	}
+
+    sprintf(buff, "\tn%p[label=\"", theTree);
+	dotSpec.append(buff);
+    text = this->getText(theTree);
+    for (std::size_t j = 0; j < text.size(); j++)
+    {
+            switch(text[j])
+            {
+                case '"':
+                    dotSpec.append("\\\"");
+                    break;
+
+                case '\n':
+                    dotSpec.append("\\n");
+                    break;
+
+                case '\r':
+                    dotSpec.append("\\r");
+                    break;
+
+                default:
+                    dotSpec += text[j];
+                    break;
+            }
+    }
+	dotSpec->append("\"]\n");
+
+	// First produce the node defintions
+	//
+	this->defineDotNodes(theTree, dotSpec);
+	dotSpec.append("\n");
+	this->defineDotEdges(theTree, dotSpec);
+	
+	// Terminate the spec
+	//
+	dotSpec.append("\n}");
+
+	// Result
+	//
+	return dotSpec;
+}
+
+template<class ImplTraits>
+void CommonTreeAdaptor<ImplTraits>::replaceChildren( TreeType* parent, ANTLR_INT32 startChildIndex, ANTLR_INT32 stopChildIndex, TreeType* t)
+{
+	if	(parent != NULL)
+		parent->replaceChildren(startChildIndex, stopChildIndex, t);
+}
+
+template<class ImplTraits>
+CommonTreeAdaptor<ImplTraits>::~CommonTreeAdaptor()
+{
+}
+
+template<class ImplTraits>
+void CommonTreeAdaptor<ImplTraits>::defineDotNodes(TreeType* t, const StringType& dotSpec)
+{
+	// How many nodes are we talking about?
+	//
+	int	nCount;
+	int i;
+    TreeType* child;
+	char	buff[64];
+	StringType	text;
+	int		j;
+
+	// Count the nodes
+	//
+	nCount = this->getChildCount(t);
+
+	if	(nCount == 0)
+	{
+		// This will already have been included as a child of another node
+		// so there is nothing to add.
+		//
+		return;
+	}
+
+	// For each child of the current tree, define a node using the
+	// memory address of the node to name it
+	//
+	for	(i = 0; i<nCount; i++)
+	{
+
+		// Pick up a pointer for the child
+		//
+		child = this->getChild(t, i);
+
+		// Name the node
+		//
+		sprintf(buff, "\tn%p[label=\"", child);
+		dotSpec->append(buff);
+		text = this->getText(child);
+		for (j = 0; j < text.size(); j++)
+		{
+            switch(text[j])
+            {
+                case '"':
+                    dotSpec.append("\\\"");
+                    break;
+
+                case '\n':
+                    dotSpec.append("\\n");
+                    break;
+
+                case '\r':
+                    dotSpec.append("\\r");
+                    break;
+
+                default:
+                    dotSpec += text[j];
+                    break;
+            }
+		}
+		dotSpec.append("\"]\n");
+
+		// And now define the children of this child (if any)
+		//
+		this->defineDotNodes(child, dotSpec);
+	}
+	
+	// Done
+	//
+	return;
+}
+
+template<class ImplTraits>
+void CommonTreeAdaptor<ImplTraits>::defineDotEdges(TreeType* t, const StringType& dotSpec)
+{
+	// How many nodes are we talking about?
+	//
+	int	nCount;
+	if	(t == NULL)
+	{
+		// No tree, so do nothing
+		//
+		return;
+	}
+
+	// Count the nodes
+	//
+	nCount = this->getChildCount(t);
+
+	if	(nCount == 0)
+	{
+		// This will already have been included as a child of another node
+		// so there is nothing to add.
+		//
+		return;
+	}
+
+	// For each child, define an edge from this parent, then process
+	// and children of this child in the same way
+	//
+	for	(int i=0; i<nCount; i++)
+	{
+		TreeType* child;
+		char	buff[128];
+        StringType text;
+
+		// Next child
+		//
+		child	= this->getChild(t, i);
+
+		// Create the edge relation
+		//
+		sprintf(buff, "\t\tn%p -> n%p\t\t// ",  t, child);
+        
+		dotSpec.append(buff);
+
+		// Document the relationship
+		//
+        text = this->getText(t);
+		for (std::size_t j = 0; j < text.size(); j++)
+        {
+                switch(text[j])
+                {
+                    case '"':
+                        dotSpec.append("\\\"");
+                        break;
+
+                    case '\n':
+                        dotSpec.append("\\n");
+                        break;
+
+                    case '\r':
+                        dotSpec.append("\\r");
+                        break;
+
+                    default:
+                        dotSpec += text[j];
+                        break;
+                }
+        }
+
+        dotSpec.append(" -> ");
+
+        text = this->getText(child);
+        for (std::size_t j = 0; j < text.size(); j++)